SyntaxStudy
Sign Up
C Fundamental Data Types and sizeof
C Beginner 1 min read

Fundamental Data Types and sizeof

C provides several built-in data types for storing integers, floating-point numbers, and characters. The most common integer types are `char`, `short`, `int`, and `long`. Each type has a signed and unsigned variant. The `float` and `double` types store fractional numbers, with `double` offering greater precision. The exact size of each type can vary between platforms, so C provides the `sizeof` operator to query the size at compile time. The `` header (C99 and later) provides fixed-width integer types such as `int8_t`, `uint32_t`, and `int64_t`. These are invaluable when writing portable code or working with binary file formats and network protocols where you need to guarantee the exact number of bits. Always prefer fixed-width types in situations where portability matters. Variables in C must be declared before use, and in C89 they must appear at the top of a block. C99 and C11 relax this rule, allowing declarations anywhere in a block. A variable declaration gives a type and a name; an initializer assigns an initial value. Uninitialized local variables contain indeterminate (garbage) values, which is a common source of bugs.
Example
#include <stdio.h>
#include <stdint.h>   /* fixed-width types */

int main(void)
{
    /* Basic types */
    char   c  = 'A';
    short  s  = 32000;
    int    i  = -42;
    long   l  = 1000000L;
    float  f  = 3.14f;
    double d  = 2.718281828;

    /* Fixed-width types from <stdint.h> */
    uint8_t  byte  = 255;
    int32_t  word  = -100000;
    uint64_t big   = 18446744073709551615ULL;

    /* sizeof returns the size in bytes */
    printf("char:    %zu bytes\n", sizeof(char));
    printf("short:   %zu bytes\n", sizeof(short));
    printf("int:     %zu bytes\n", sizeof(int));
    printf("long:    %zu bytes\n", sizeof(long));
    printf("float:   %zu bytes\n", sizeof(float));
    printf("double:  %zu bytes\n", sizeof(double));
    printf("int32_t: %zu bytes\n", sizeof(int32_t));

    printf("c=%c  s=%d  i=%d  l=%ld\n", c, s, i, l);
    printf("f=%.2f  d=%.9f\n", f, d);
    printf("byte=%u  word=%d\n", byte, word);

    return 0;
}