Datatypes in C Programming.

Sujith V S - Dec 7 '23 - - Dev Community

A data type is a classification that specifies which type of value a variable can hold.
int age;
In the above initialisation code the datatype is int. The variable age can only store integer value.
The datatype also tells the compiler to allocate specific bits of memory according to the datatype used in the variable.
In the code above the variable with int value can store 4 bytes of data.

Important datatypes in C

  • int (4 bytes) | %d for printing
  • double (8 bytes) | %lf for printing
  • float (4 bytes) | %f for printing
  • char (1 bytes) | %c for printing
  • bool (1 bytes) | %d for printing

The above list shows the main 4 datatypes in C along with its size and format specifier.

int
The int data type is used to declare integer variables.The int type is commonly used to represent whole numbers (integers) without any decimal places.
int num1 = 42;

char
The char data type in C is used to represent individual characters. It is typically used to store single characters, such as letters, digits, and special symbols.
char myChar = 'A';
We must use only single quot for char.
Characters are internally stored as integers. Each character corresponds to a numerical value according to the ASCII. For example, in ASCII, the character 'A' is represented by the integer value 65, 'B' by 66, and so on.

#include <stdio.h>      
int main() {

  char character = 'z'; 

  printf("%c", character);
  printf(" %d", character);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

float and double
float and double is used to store decimal and exponential values. Only difference between float and double is its size.
float myFloat = 3.14159;
double myDouble = 3.14159265359;

#include <stdio.h>      
int main() {

  double number = 12.45;
  printf("%lf", number);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

In the above code the output is 12.450000. The float and double will have 6 digits after the decimal points that is the reason for the additional zeros in the above output.
If we want to avoid those values and we need only 2 digits after decimal points use .2 after %.

#include <stdio.h>      
int main() {
  double number = 12.45;
  float number1 = 10.9f; //f is to indicate its a float value 
                           rather than a double value.
  printf("%.2lf", number);

  printf("\n%.1f", number1);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

bool
C provides a built-in data type called bool to represent Boolean values. This allows you to store and manipulate logical states directly, enhancing code readability and type safety.
Holds two possible values: true and false.
Represented internally as 1 for true and 0 for false.

bool isLoggedIn = true; // Initialize to true
bool isDone = false; // Initialize to false
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player