In this lesson:
- what a variable actually is (and what's happening in memory when you make one)
- the four foundational C types:
int,float,char,bool - declaring vs initializing vs assigning, three operations that look similar
- type-correctness as your first line of defense against bugs
- the difference between a single character
'A'and a one-character string"A"
A variable is a named box
When you write int score = 42;, you are doing three things at once:
- asking the compiler to set aside memory for a value,
- telling it the value will be an integer (
int), - giving that location a name (
score) you can use later.
You can read from the box (printf("%d", score);) or overwrite it (score = 100;). The name is for your benefit; the CPU just sees an address.
Memory: [........][..42....][........]
β
scoreThe four types you need first
C has many types, but four cover almost everything early on:
| Type | Holds | Example value | Size (typical) |
|---|---|---|---|
int |
whole number, positive or negative | 42, -7, 0 |
4 bytes |
float |
number with a fractional part | 3.14f, -0.5f |
4 bytes |
char |
a single character (or a tiny integer 0-255) | 'A', '?', '\n' |
1 byte |
bool |
a truth value | true or false |
1 byte |
bool is not built into C, you get it by including <stdbool.h>. Without that header, C programmers traditionally used int where 0 is false and any non-zero value is true.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int score = 95; // whole number
float pi = 3.14f; // fractional; 'f' marks it as float
char grade = 'A'; // single character in single quotes
bool passed = true; // from <stdbool.h>
printf("score=%d pi=%.2f grade=%c passed=%d\n",
score, pi, grade, passed);
return 0;
}The funny %d, %.2f, %c are format specifiers, they tell printf how to interpret each argument. They must match the variable's type, or you'll get garbage.
Declare, initialize, assign
These three operations look similar but are distinct:
int x; // declare: reserve a box. Value is undefined garbage.
x = 5; // assign: put 5 in the box.
int y = 7; // declare and initialize in one line. Preferred.
y = y + 1; // assign again: replace the value in the box.Always initialize. A declared-but-never-initialized variable contains whatever bits were already in that memory location, unpredictable, machine-dependent, and a common source of "it works on my machine" bugs. Modern compilers warn about this; treat that warning as an error.
int x; // β undefined value
printf("%d\n", x); // prints garbage (could even crash)Type rules and conversions
C will silently convert between numeric types in many situations. This is convenient but treacherous:
int n = 5;
float f = 2.0f;
float avg = n / 2; // integer division first! avg == 2.0, not 2.5
float ok = n / 2.0f; // float division. ok == 2.5The first one bites every beginner. Both operands of / are int, so C performs integer division, fractional parts are discarded before the result gets stored into avg. To force float math, at least one operand must be a float.
Other quirks to expect:
char c = 65;is the same aschar c = 'A';(ASCII code for A is 65).int n = 3.9f;stores3, the fractional part is truncated, not rounded.- Mixing signed and unsigned types causes some very confusing comparisons. We'll cover this in detail in later modules.
'A' vs "A"
This trips up nearly everyone in their first week:
char single = 'A'; // one character. Single quotes.
char *string = "A"; // a one-character string. Double quotes.'A' is a single byte holding the value 65. "A" is two bytes, 'A' followed by a hidden '\0' (null terminator) marking the end of the string. We'll explore this fully in the Arrays and Strings lesson. For now: characters get single quotes, text gets double quotes.
Gotchas
- Uninitialized variables hold garbage. Always initialize at declaration:
int x = 0;, notint x;. Compile with-Wallto catch this. - Integer division silently truncates.
5 / 2is2, not2.5. To get the fraction, make one operand a float:5 / 2.0f. - Floats can't hold every decimal exactly.
0.1f + 0.2fis not exactly0.3f. For money and other exact decimals, use integers (cents, not dollars). - Format specifier mismatch is undefined behavior. Passing a
floatto%ddoesn't just print wrong, it can corrupt subsequent arguments. Match the type every time. - Single quotes vs double quotes.
'A'is achar."A"is a string. They are not interchangeable.
TL;DR
- A variable is a named memory location plus a type. The type tells the compiler how big it is and how to interpret the bits.
- C's foundational types:
int(whole),float(fractional),char(one character),bool(true/false, via<stdbool.h>). - Declare and initialize on the same line, uninitialized variables hold garbage.
- Beware integer division:
5 / 2 == 2. Force float math when you want a fraction. - Match
printfformat specifiers to the variable's type, or expect nonsense output.