Variables and Data Types

Variables and Data Types in C: In Python, a variable is a sticky note. You write and later , and the note simply moves to a different object.

The Analogy: Renting Shelf Space by the Centimetre

In Python, a variable is a sticky note. You write x = 5 and later x = "hello", and the note simply moves to a different object. Nothing had to be measured in advance.

In C, a variable is rented shelf space of an exact size, at a fixed address, with a permanent label. When you write int score;, the compiler reserves precisely four bytes somewhere on the stack and agrees to call those four bytes score for as long as the enclosing block runs. Those four bytes will be interpreted as a whole number, forever. You cannot later decide they hold text.

This is why declaring a type is not paperwork. The compiler physically cannot lay out the shelf until it knows how wide each box is.


Syntax or Core Structure

A declaration is a type followed by a name. An initialiser is optional but should not be.

#include <stdio.h>

int main(void) {
    int    current_year = 2026;      // whole number
    float  temperature  = 98.6f;     // single-precision decimal
    double precise_pi   = 3.14159265358979;
    char   grade        = 'A';       // ONE character, single quotes

    printf("Year:  %d\n", current_year);
    printf("Temp:  %.1f\n", temperature);
    printf("Pi:    %.5f\n", precise_pi);
    printf("Grade: %c\n", grade);

    return 0;
}

Output:

Year:  2026
Temp:  98.6
Pi:    3.14159
Grade: A

Two details in that snippet cause real confusion:

  • 'A' in single quotes is a character, a one-byte integer. "A" in double quotes is a string, which is two bytes: the letter and a hidden terminating zero. They are not interchangeable, and mixing them is a compile error.
  • The f suffix on 98.6f says "this literal is a float". Without it, 98.6 is a double, and the compiler quietly narrows it on assignment. With -Wall -Wextra you may get a warning about the lost precision.

The primitive types

TypeTypical sizeWhat it holdsprintf specifier
char1 byteone character, or a tiny integer%c
short2 bytessmall whole numbers%hd
int4 byteswhole numbers, the default choice%d
long4 or 8 byteslarger whole numbers%ld
long long8 bytesvery large whole numbers%lld
float4 bytes~7 significant digits%f
double8 bytes~15 significant digits%lf in scanf, %f in printf
_Bool1 byte0 or 1 (via <stdbool.h>)%d

Note the word "typical". The C standard guarantees only minimum ranges, not exact sizes: it promises int is at least 16 bits and that sizeof(char) == 1, and leaves the rest to the platform. On a 64-bit Linux machine long is 8 bytes; on 64-bit Windows it is 4. Code that assumes otherwise breaks when it moves.


Technical Depth: Signedness, Overflow, and sizeof

Every integer type comes in a signed and an unsigned flavour. Signed types spend one bit on the sign; unsigned types use every bit for magnitude.

#include <stdio.h>
#include <limits.h>

int main(void) {
    printf("int is %zu bytes, from %d to %d\n",
           sizeof(int), INT_MIN, INT_MAX);
    printf("unsigned int is %zu bytes, from 0 to %u\n",
           sizeof(unsigned int), UINT_MAX);
    printf("char is %zu byte, double is %zu bytes\n",
           sizeof(char), sizeof(double));
    return 0;
}

Output (on a typical 64-bit machine):

int is 4 bytes, from -2147483648 to 2147483647
unsigned int is 4 bytes, from 0 to 4294967295
char is 1 byte, double is 8 bytes

sizeof is a compile-time operator, not a function, and it yields a size_t — which is why the specifier is %zu and not %d. Never hardcode 4 where you mean sizeof(int).

The unsigned trap

#include <stdio.h>

int main(void) {
    unsigned int count = 0;
    count = count - 1;          // does NOT become -1
    printf("count = %u\n", count);

    int small = 2147483647;     // INT_MAX
    small = small + 1;          // undefined behaviour, not a wrap
    printf("small = %d\n", small);
    return 0;
}

Output (one possible result):

count = 4294967295
small = -2147483648

These two lines look similar and are fundamentally different. Unsigned arithmetic is defined to wrap around modulo 2^32, so 0 - 1 is genuinely 4294967295. Signed overflow is undefined behaviour: the compiler is entitled to assume it never happens, and optimisers really do delete code based on that assumption. The output above is what usually appears, not what is guaranteed.

The practical rule: use unsigned when you are doing bit manipulation or genuinely counting things that cannot be negative, and be very careful when an unsigned value can reach zero and then be decremented.

Constants

#define MAX_USERS 100        // preprocessor text substitution, no type
const int max_users = 100;   // a real typed, read-only variable

Prefer const. It has a type, it respects scope, it appears in the debugger, and the compiler can check how you use it. #define is a blind find-and-replace performed before the compiler sees your code.

Implicit conversion

#include <stdio.h>

int main(void) {
    int    a = 7, b = 2;
    double bad  = a / b;              // integer division happens FIRST
    double good = (double)a / b;      // one operand promoted, so real division

    printf("bad = %.2f, good = %.2f\n", bad, good);

    double d = 9.99;
    int    truncated = d;             // 9, not 10 -- it truncates, never rounds
    printf("truncated = %d\n", truncated);
    return 0;
}

Output:

bad = 3.00, good = 3.50
truncated = 9

a / b is computed entirely in integers and only then widened to double, so the fractional part is gone before the assignment happens. Casting one operand is what forces the whole expression into floating point.


Real World Example: A Sensor Reading Record

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    /* One reading from a temperature probe on an embedded board. */
    const int      sensor_id      = 7;
    unsigned char  battery_pct    = 84;      /* 0-255 fits in one byte */
    float          celsius        = 21.75f;
    bool           needs_service  = false;
    char           status_code    = 'K';     /* K = ok, F = fault */

    float fahrenheit = celsius * 9.0f / 5.0f + 32.0f;

    printf("Sensor #%d  [%c]\n", sensor_id, status_code);
    printf("  Temperature: %.2f C  (%.2f F)\n", celsius, fahrenheit);
    printf("  Battery:     %u%%\n", battery_pct);
    printf("  Service due: %s\n", needs_service ? "yes" : "no");

    printf("\nRecord size: %zu bytes\n",
           sizeof(sensor_id) + sizeof(battery_pct) +
           sizeof(celsius) + sizeof(needs_service) + sizeof(status_code));
    return 0;
}

Output:

Sensor #7  [K]
  Temperature: 21.75 C  (69.95 F)
  Battery:     84%
  Service due: no

Record size: 11 bytes

Choosing unsigned char for the battery percentage is not premature optimisation; it is the kind of decision that matters when the same struct is stored a million times or transmitted over a slow radio link. 9.0f / 5.0f is written in floating point deliberately — 9 / 5 would be integer division and would silently give 1, turning the conversion into nonsense. And %% is how you print a literal percent sign, since % alone begins a specifier.


Common Mistakes

  1. Using "A" where 'A' is meant. Double quotes make a two-byte string, not a character.
  2. Integer division by accident: 5 / 2 is 2, and no amount of assigning it to a double will recover the .5.
  3. Reading an uninitialised variable. It holds leftover stack bytes, which is undefined behaviour rather than a reliable zero.
  4. Mismatching specifier and type, such as printf("%d", 3.7) or scanf("%f", &a_double). The scanf version corrupts adjacent memory because it writes four bytes into an eight-byte slot.
  5. Assuming int is always 4 bytes or long is always 8. Use sizeof, or the exact-width types in <stdint.h> such as int32_t.
  6. Decrementing an unsigned variable past zero and expecting a negative number. You get a very large positive number instead.
  7. Comparing floats with ==. 0.1f + 0.2f == 0.3f is false; compare against a small tolerance instead.
  8. Reaching for #define for every constant when const gives you a type and scope for free.

Best Practices

  • Declare and initialise in the same statement, always.
  • Use int for ordinary counting, double for ordinary decimals, and reach for narrower types only when size genuinely matters.
  • Prefer <stdint.h> types (int32_t, uint8_t) whenever an exact width is part of the contract, such as file formats or network packets.
  • Use sizeof rather than literal byte counts, and print it with %zu.
  • Prefer const over #define for typed constants.
  • Use snake_case for variable names; it is the dominant convention in C codebases including the kernel.
  • Cast explicitly when you intend a conversion, so a reader can see it was on purpose.
  • Include <stdbool.h> and use bool, true, and false rather than bare 0 and 1.

Practice Exercises

  1. Measure Your Machine: Print the sizeof of char, short, int, long, long long, float, double, and long double on your computer, and compare the numbers against the table above.
  2. The Vanishing Half: Write a program that computes the average of 7 and 8 two ways, once with integer division and once with a cast, and print both. Explain in a comment why the first is wrong.
  3. Wrap Around: Set an unsigned char to 255 and add 1; set it to 0 and subtract 1. Print both results and explain the values you get in terms of the byte's range.
  4. Temperature Table: Using a const step value, print a two-column table of Celsius to Fahrenheit from 0 to 100 in steps of 10, with exactly one decimal place in each column.