Junior — Middle
Can you explain the differences between various int types in C, such as size_t, long, short, and int?
sobes.tech AI
Answer from AI
In the C language, different integer types differ in size and range:
short— usually 16 bits, can store approximately from -32,768 to 32,767 (signed type).int— usually 32 bits on modern systems, range depends on platform, often from -2,147,483,648 to 2,147,483,647.long— size depends on platform, typically 32 bits on 32-bit systems and 64 bits on 64-bit systems.size_t— unsigned type designed for storing object sizes and array indices. Its size depends on architecture (e.g., 32 or 64 bits). It guarantees to hold the maximum size of any object in memory.
Main differences:
size_tis always unsigned and used for sizes and indices.short,int,longcan be signed or unsigned (ifunsignedis specified), and their size depends on the platform.
Example of using size_t:
#include <stdio.h>
#include <stddef.h>
int main() {
size_t length = 10;
int array[10];
for (size_t i = 0; i < length; i++) {
array[i] = (int)i;
printf("%d ", array[i]);
}
return 0;
}
Here, size_t is used for array indexing, which is safe and standard-compliant.