Data Types
Dive deeper into primitive types, type modifiers, and type casting in C.
Primitive Data Types
C provides four fundamental primitive types that serve as the building blocks for all data. The char type holds a single byte and is used for characters and small integers. The int type is the natural word size of the machine and is the most commonly used integer type. The float and double types represent single and double precision floating point numbers respectively. Understanding these types and their ranges is critical for writing correct and efficient C programs.
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(void) {
printf("char: %d to %d\n", CHAR_MIN, CHAR_MAX);
printf("int: %d to %d\n", INT_MIN, INT_MAX);
printf("long: %ld to %ld\n", LONG_MIN, LONG_MAX);
printf("float max: %e\n", FLT_MAX);
printf("double max: %e\n", DBL_MAX);
return 0;
}
Type Modifiers
Type modifiers alter the size or sign of a base type. The short and long modifiers change the storage size of integers, with short being at least 16 bits and long being at least 32 bits. The signed and unsigned modifiers determine whether a type can represent negative values. An unsigned int uses all its bits for magnitude, effectively doubling the maximum positive value at the cost of not representing negative numbers.
#include <stdio.h>
int main(void) {
short int smallNum = 32767;
long int bigNum = 2147483647L;
long long int hugeNum = 9223372036854775807LL;
unsigned int positive = 4294967295U;
printf("short: %hd\n", smallNum);
printf("long: %ld\n", bigNum);
printf("long long: %lld\n", hugeNum);
printf("unsigned: %u\n", positive);
printf("Size of short: %zu\n", sizeof(short));
printf("Size of long: %zu\n", sizeof(long));
printf("Size of long long: %zu\n", sizeof(long long));
return 0;
}
Type Casting
Type casting converts a value from one type to another. Implicit casting happens automatically when the compiler promotes a narrower type to a wider type in an expression. Explicit casting uses the cast operator to force a conversion, which can result in data loss if the target type cannot represent the original value. Being mindful of casting is important to avoid subtle bugs such as integer overflow and truncation of floating point values.
#include <stdio.h>
int main(void) {
/* Implicit casting: int promoted to double */
int intVal = 7;
double result = intVal / 2.0;
printf("7 / 2.0 = %.2f\n", result);
/* Integer division without cast */
int a = 7, b = 2;
printf("7 / 2 (int) = %d\n", a / b);
/* Explicit cast to get floating point division */
double precise = (double)a / (double)b;
printf("7 / 2 (cast) = %.2f\n", precise);
/* Narrowing cast: data loss */
double pi = 3.14159;
int truncated = (int)pi;
printf("Truncated pi: %d\n", truncated);
return 0;
}