These are the notes for C episode 2. You will learn why programs need variables, how to declare, assign and change one, which box (data type) to pick, why the printf format specifier must match the type, what sizeof tells you, how an int overflows, and how const locks a value. Every example below was compiled with gcc -O2 main.c -o main -lm (gcc 13) and the output shown is the real output.
The problem: one price copied everywhere
Meena aunty runs a tiffin service. One tiffin costs ₹60, and her son wrote a C program that prints bills:
#include <stdio.h>
int main() {
printf("Tiffin x 2 = %d\n", 60 * 2);
printf("Tiffin x 3 = %d\n", 60 * 3);
printf("Tiffin x 5 = %d\n", 60 * 5);
return 0;
}
Output:
Tiffin x 2 = 120
Tiffin x 3 = 180
Tiffin x 5 = 300
Vegetables get expensive and the price goes up to ₹70. In a hurry we change the first and third lines and miss the middle one:
printf("Tiffin x 2 = %d\n", 70 * 2);
printf("Tiffin x 3 = %d\n", 60 * 3);
printf("Tiffin x 5 = %d\n", 70 * 5);
Output:
Tiffin x 2 = 140
Tiffin x 3 = 180
Tiffin x 5 = 350
Three tiffins should cost 210, not 180. Meena aunty loses ₹30 on every such order, and the compiler says nothing, because to it this code is perfectly fine: no error, wrong bill.
Why did it break?
- One fact (the price) is copied in many places.
- Change one copy, forget another, and the output is wrong.
- Reading
60 * 3, nobody can tell what60means. A price? A discount? A room number?
The fix: write the price once, give it a name, and use the name everywhere. That named box is a variable.
Variables: a labelled dabba
Think of the steel dabbas in a kitchen. The label (sugar, tea, salt) is the variable's name. What's inside is the value. You can empty the dabba and refill it, and the label stays.
#include <stdio.h>
int main() {
int price = 70;
printf("Tiffin x 2 = %d\n", price * 2);
printf("Tiffin x 3 = %d\n", price * 3);
printf("Tiffin x 5 = %d\n", price * 5);
return 0;
}
Output:
Tiffin x 2 = 140
Tiffin x 3 = 210
Tiffin x 5 = 350
Now change only the first line to int price = 80; and the whole bill updates:
Tiffin x 2 = 160
Tiffin x 3 = 240
Tiffin x 5 = 400
Anatomy of a variable
| Part | In int price = 70; |
Meaning |
|---|---|---|
| Type | int |
what kind of box (whole numbers) |
| Name | price |
the label you use in code |
= |
assignment | put the value on the right into the box on the left |
| Value | 70 |
what goes inside |
; |
end | ends the statement |
int price; // declare: make the box
price = 70; // assign: fill the box
int cups = 3; // both together: initialize
price = 80; // change it later: do NOT write int again
You write the type only when you make the box. In C, = means "put into", not the maths "is equal to". (Comparison is ==, covered in the operators episode.)
int drops decimals silently: the missing 50 paise
For regular customers the price becomes ₹62.50. If we keep the same int box:
#include <stdio.h>
int main() {
int price = 62.5;
printf("Price = %d\n", price);
printf("Tiffin x 2 = %d\n", price * 2);
return 0;
}
Output:
Price = 62
Tiffin x 2 = 124
The bill should be 125. gcc compiles this with no error and no warning (this is very different from Java, which refuses to compile it). An int holds only whole numbers, so C cuts off everything after the decimal point. It does not round: 62.9 would also become 62.
Tip:
gcc -Wall -Wextrastill says nothing here.gcc -Wconversiondoes warn about the lost fraction. It is a good flag to turn on while learning.
Data types: the right container for each thing
| Kitchen | C type | Holds |
|---|---|---|
| Egg tray (no half eggs) | int |
whole numbers: 70, -5 |
| Measuring jug (0.5 L, 1.25 L) | float / double |
decimals: 62.5 |
| One-letter size tag (S, M, L) | char |
one character: 'A' |
So the right box for the price is float, printed with %f:
#include <stdio.h>
int main() {
float price = 62.5;
printf("Price = %f\n", price);
printf("Price = %.2f\n", price);
printf("Tiffin x 2 = %.2f\n", price * 2);
return 0;
}
Output:
Price = 62.500000
Price = 62.50
Tiffin x 2 = 125.00
%fprints six decimal places by default.%.2fprints exactly two, which is what you want for money. The 50 paise are back.
Format specifiers must match the type
A printf format string is like a form. Each blank expects one kind of answer: "Age: ___ years" expects a whole number, "Weight: ___ kg" expects a decimal, "Section: ___" expects one letter.
| Specifier | Expects | Example |
|---|---|---|
%d |
int |
printf("%d", 70); |
%f |
float or double |
printf("%f", 62.5); |
%.2f |
float or double, 2 decimals |
printf("%.2f", 62.5); → 62.50 |
%c |
char |
printf("%c", 'A'); |
%lld |
long long |
printf("%lld", 8000000000LL); |
%zu |
the result of sizeof (size_t) |
printf("%zu", sizeof(int)); |
%u |
unsigned int |
printf("%u", 4294967295u); |
What happens if you put the wrong thing in a blank?
#include <stdio.h>
int main() {
float price = 62.5;
printf("Price = %d\n", price);
return 0;
}
gcc warns (and even suggests the fix):
main.c:5:22: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
5 | printf("Price = %d\n", price);
| ~^ ~~~~~
| | |
| int double
| %f
The program still runs, and prints a garbage value, a random-looking number such as:
Price = 400418600
Run it again and you may get a different number. Rule for your notebook: the specifier must always match the variable's type, and never ignore a warning.
Notice the warning says double, not float: when a float is passed to printf, C automatically promotes it to double. That is why %f works for both float and double.
char: a letter is secretly a number
char grade = 'A';
- Single quotes
'A'make one character, achar. - Double quotes
"A"make a string, which is not achar. Strings get their own episode later. - Inside memory, a
charis a small number. CapitalAis 65, its ASCII code.
#include <stdio.h>
int main() {
char grade = 'A';
printf("Grade: %c\n", grade);
printf("Code: %d\n", grade);
printf("Next: %c\n", grade + 1);
return 0;
}
Output:
Grade: A
Code: 65
Next: B
Same box, two ways to read it: %c shows the character, %d shows the number. 'A' + 1 is 66, which is 'B'.
sizeof: how big is each box?
Boxes come in sizes, like a tiny spice dabba, a medium everyday dabba and a big drum for a year's wheat. Memory size is measured in bytes, and the sizeof operator tells you a type's size. Its result is printed with %zu.
#include <stdio.h>
int main() {
printf("char: %zu byte\n", sizeof(char));
printf("int: %zu bytes\n", sizeof(int));
printf("float: %zu bytes\n", sizeof(float));
printf("double: %zu bytes\n", sizeof(double));
printf("long long: %zu bytes\n", sizeof(long long));
return 0;
}
Output (on a typical 64-bit Linux PC):
char: 1 byte
int: 4 bytes
float: 4 bytes
double: 8 bytes
long long: 8 bytes
These are the sizes on this machine. The C standard only sets minimums (for example, int must be at least 2 bytes), so on another computer an int could be a different size. When in doubt, ask sizeof. sizeof(char) is always 1 by definition.
C's basic types (typical 64-bit PC)
| Type | Size | Example | Range / precision | printf |
|---|---|---|---|---|
char |
1 byte | 'A' |
-128 to 127 | %c |
int |
4 bytes | 70 |
about ±2.1 billion (2,147,483,647) | %d |
float |
4 bytes | 62.5 |
about 7 significant digits | %f |
double |
8 bytes | 62.5 |
about 15 significant digits | %f (or %lf) |
long long |
8 bytes | 8000000000 |
about ±9.2 × 10¹⁸ | %lld |
floatis accurate to about 7 digits anddoubleto about 15, which is why most programmers usedoublefor decimals.- Put
unsignedin front (unsigned int) and the type cannot hold negatives, but its positive range doubles (unsigned intgoes up to 4,294,967,295).
A quick look at that precision difference:
float f = 0.1;
double d = 0.1;
printf("%.10f\n%.10f\n", f, d);
Output:
0.1000000015
0.1000000000
Overflow: when a number is too big
A viral video's views are stored in an int, at 2,147,483,647, the largest value an int can hold. One more view comes in:
#include <stdio.h>
int main() {
int views = 2147483647;
views = views + 1;
printf("Views: %d\n", views);
return 0;
}
Output:
Views: -2147483648
No error. The box was full, so the number wrapped round to the most negative value, like an old car odometer going from 99999 to 00000. This is overflow. C assumes the programmer knows what they are doing.
Interview detail: for signed types like
int, overflow is actually undefined behaviour in the C standard. On normal PCs you usually see the wrap-around above, but the compiler is allowed to do anything, so never rely on it. Unsigned types are defined to wrap around.
The fix is a bigger box:
#include <stdio.h>
int main() {
long long population = 8000000000;
printf("World: %lld\n", population);
return 0;
}
Output:
World: 8000000000
Rule: if a number can get really big, use long long and print it with %lld.
Constants with const
Some values must never change, like the 5% GST on food. If a new helper accidentally writes GST = 0.18;, every bill goes wrong. Lock the dabba with const:
#include <stdio.h>
int main() {
const float GST = 0.05;
GST = 0.18;
printf("%f\n", GST);
return 0;
}
gcc refuses to compile it:
main.c:5:9: error: assignment of read-only variable 'GST'
The lock worked: the mistake is caught before the program ever runs. Constants are usually named in CAPITAL letters so you can spot them from far away. A const variable must be given its value when it is declared, because you cannot assign it later.
Naming rules
- Allowed: letters, digits and underscore
_(price,total2,per_box). - A name cannot start with a digit (
2cupsis invalid). - No spaces, no
-or@(total price,per-boxare invalid). - Not a keyword (
int,return,float…). - Case sensitive:
priceandPriceare two different variables. - Use meaningful names:
price, notp.
Common mistakes (and the real gcc messages)
| Mistake | Code | What gcc says |
|---|---|---|
| Wrong name or case | int price = 60; printf("%d\n", Price); |
error: 'Price' undeclared (first use in this function); did you mean 'price'? |
| Name starts with a digit | int 2cups = 2; |
error: invalid suffix "cups" on integer constant |
| Double quotes for a char | char grade = "A"; |
warning: initialization of 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion] |
| Wrong specifier | float price = 62.5; printf("%d", price); |
warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=] |
Decimal into int |
int price = 62.5; |
no message at all; prints 62 |
| Changing a constant | const float GST = 0.05; GST = 0.18; |
error: assignment of read-only variable 'GST' |
| Using a variable you never filled | int total; printf("%d", total); |
often no message at all |
The first one, live: gcc points at line 5 and even suggests the right name.
main.c:5:20: error: 'Price' undeclared (first use in this function); did you mean 'price'?
5 | printf("%d\n", Price);
| ^~~~~
| price
Make the P small and it prints 60.
The last mistake is the most dangerous. An uninitialised local variable holds whatever was already lying in that memory: you might see 0, you might see a garbage number, and it can change between runs or compilers. Always give a variable a starting value: int total = 0;. (gcc -Wall can sometimes warn with 'total' is used uninitialized.)
Mini project: Meena aunty's monthly tiffin bill
#include <stdio.h>
int main() {
const float GST = 0.05;
char plan = 'V';
int days = 22;
float price = 62.5;
float total = days * price;
printf("Plan: %c Days: %d\n", plan, days);
printf("Subtotal: %.2f\n", total);
printf("GST: %.2f\n", total * GST);
printf("Total: %.2f\n", total + total * GST);
return 0;
}
Output:
Plan: V Days: 22
Subtotal: 1375.00
GST: 68.75
Total: 1443.75
The right type in every box (char for the plan letter, int for days, float for money, const for GST) and the right specifier in every blank.
Practice
- Change the tiffin bill to 30 days at ₹75.50. What are the subtotal, GST and total?
- Print
'a','Z'and'0'with both%cand%d. - Print
sizeof(short)andsizeof(long)on your machine. - Make each of today's errors on purpose (
Price,2cups,"A",%dwith a float, changing aconst) and read the gcc message. - Which type would you use for a person's age, a cricket batting average, a blood group letter and the number of YouTube views across all videos in the world?
Solutions and hints
1. Set int days = 30; and float price = 75.50;. Output:
Plan: V Days: 30
Subtotal: 2265.00
GST: 113.25
Total: 2378.25
2. printf("%c %d | %c %d | %c %d\n", 'a','a','Z','Z','0','0'); prints a 97 | Z 90 | 0 48. Note that the character '0' is 48, not 0.
3. printf("%zu %zu\n", sizeof(short), sizeof(long)); prints 2 8 on 64-bit Linux and macOS. On 64-bit Windows long is 4 bytes, which is exactly why you ask sizeof instead of guessing.
4. Compare your messages with the common-mistakes table above.
5. Age: int. Batting average: double (or float). Blood group letter: char. Total world views: long long (or unsigned long long), because it can easily pass 2.1 billion.
Quick quiz
What will this code print?
int price = 99.9;
printf("%d\n", price);
- A.
99.9 - B.
100 - C.
99 - D. Compile error
Answer
C: 99. An int keeps only the whole part. C chops off .9 without rounding and without an error. (Verified: the program prints 99.)
Interview questions
- What is the difference between declaration, assignment and initialisation?
- What happens when you store
62.5in anintin C? How is that different from Java? - Why must the printf format specifier match the argument type? What is a garbage value?
- Why does
%fwork for bothfloatanddoubleinprintf? (default argument promotion) - Is
sizeof(int)always 4? What does the C standard guarantee? - What is the ASCII value of
'A','a'and'0'? - What is integer overflow? Is signed overflow defined in C?
- What does
constdo, and why name constants in capitals?
Summary
- A variable is a labelled box:
type name = value;. Change the value in one place and every use updates. intsilently drops decimals; usefloatordoublefor them, and%.2ffor money.- The format specifier must match the type:
%d,%f,%.2f,%c,%lld,%zu. - A
charis a small number:'A'is 65. sizeoftells you a type's size in bytes on your machine.- An
intoverflows past 2,147,483,647; uselong longfor big counts. constlocks a value, and the compiler stops anyone who tries to change it.
Next episode: operators. Four friends split a ₹250 bill and C says each pays ₹62. Where did the rest go? Also: what % does, ++, and why true is 1.