Chapter 2: Variables, Data Types, and Operators
In the previous chapter, we successfully ran our first program. Now, we need to learn how to store and manipulate data. Unlike Python, where you can simply assign a value to a name, C requires you to explicitly declare the "data type" of every variable you use. This is called static typing, and it is a key reason why C programs are so fast.
1. Declaring Variables
To declare a variable, you state the data type followed by the variable name. If you try to put a decimal number into an integer variable, C will either truncate the decimal or throw an error depending on the compiler.
int age = 25;
float height = 5.9;
char initial = 'A';
2. Essential Data Types
- int: Stores whole numbers (e.g., 10, -500).
- float/double: Stores numbers with decimals.
doubleprovides more precision thanfloat. - char: Stores a single character (e.g., 'A', 'z'). Note the use of single quotes.
3. Operators
Operators perform operations on variables and values. C includes:
- Arithmetic:
+,-,*,/, and the modulus operator%(which gives the remainder of a division). - Assignment:
=,+=,-=. - Comparison:
==(equal to),!=(not equal to),>,<,>=,<=.
4. Printing Variables with Format Specifiers
To print variables in C, you must use "format specifiers" inside printf. These tell C what kind of data to expect:
printf("Age: %d", age); // %d for int
printf("Height: %.2f", height); // %.2f for float (2 decimals)
printf("Initial: %c", initial); // %c for char
Common Beginner Mistakes
- Uninitialized Variables: If you declare a variable but don't give it a value, it will contain "garbage" data from the computer's memory. Always initialize your variables!
- Using Wrong Specifiers: Printing an
intwith%for afloatwith%dwill result in completely nonsensical output. - Semicolons: I cannot stress this enough—if you forget the semicolon after a declaration, the code will not compile.
Try It Yourself
- Declare an integer for your age and a float for your height.
- Perform a simple calculation (e.g., age + 5) and store it in a new variable.
- Print both the original variables and the result using
printf.
Type Casting in C
C is strict about data types, so mixing them often requires an explicit cast. This is especially important with division, where two integers will produce an integer result unless you cast one to a float.
int a = 7, b = 2;
printf("%d\n", a / b); // prints 3
printf("%f\n", (float)a / b); // prints 3.500000
Operator Precedence
Just like in math, C operators follow a strict order of evaluation — multiplication and division happen before addition and subtraction. When in doubt, use parentheses to make your intent explicit and avoid subtle bugs.
int result = 2 + 3 * 4; // 14, not 20
int clearer = 2 + (3 * 4); // also 14, but easier to read
CodeMaster Academy