Module I · Basics of C · Lecture 3
🎯 Why This Matters
Every program you’ll ever write is, at its core, about naming things and storing values in them. A shopping app needs a name for “total price.” A game needs a name for “player score.” A weather app needs a name for “current temperature.” In C, these names are called identifiers, and the boxes they label are called variables.
But C won’t let you name things just anyhow. It has strict rules about what makes a valid name, and a reserved list of words you’re not allowed to use as names at all. Get this wrong, and your program won’t even compile — so before you write a single meaningful line of C code, you need to master this naming system, and then practice it through real, runnable code examples.
🧠 Think of It Like Labeling Boxes in a Warehouse
Imagine a warehouse full of storage boxes. Each box:
- Needs a label so workers know what’s inside without opening it (this is the identifier)
- Can only hold one type of item at a time — a box labeled “screws” shouldn’t suddenly hold water bottles (this is the data type)
- Can have its contents replaced — you can empty a box and refill it with a new batch (this is what makes it a variable — the value can vary)
💡 Key Idea: A variable is really just a labeled, typed storage location in memory. The identifier is the label; the data type tells the compiler how big a box to reserve.
Now let’s break down the three concepts from today’s lecture — identifiers, keywords, and variables — one at a time, with full working code examples for each.
1️⃣ Identifiers: The Naming Rules
An identifier is the name you give to a variable, function, or any other user-defined item in your program. But C enforces a strict set of rules about what counts as a valid identifier.
✅ The Rules for a Valid Identifier
- Must begin with a letter (A–Z, a–z) or an underscore
_— never a digit - After the first character, it can contain letters, digits (0–9), and underscores
- No spaces or special symbols are allowed (no
@,-,%,#, etc.) - C is case-sensitive —
score,Score, andSCOREare three completely different identifiers - It cannot be a reserved keyword (like
int,for, orreturn) — more on this below - There’s no fixed length limit in modern C, but extremely long names hurt readability
🔍 Valid vs. Invalid: Side by Side
| Identifier | Valid? | Why |
|---|---|---|
totalMarks | ✅ Valid | Starts with a letter, no illegal characters |
_count | ✅ Valid | Starts with an underscore — legal, though unconventional for beginners |
student1 | ✅ Valid | Digit appears after the first character — perfectly fine |
1student | ❌ Invalid | Starts with a digit — not allowed |
total marks | ❌ Invalid | Contains a space |
total-marks | ❌ Invalid | Hyphen is not a permitted character |
float | ❌ Invalid | It’s a reserved keyword |
marks% | ❌ Invalid | Contains a special symbol |
Marks and marks | ✅ Both valid, but different | C treats them as two separate identifiers |
💡 Real-world parallel: Think of identifiers like usernames on a website. You can’t have a username that starts with a number on some platforms, you can’t use spaces, and “Ajay” and “ajay” might even be treated as two separate accounts. C applies the same discipline to variable names.
💻 Code Example 1: A Program That Deliberately Breaks the Rules
The best way to internalize naming rules is to see them fail. Here’s a short program with several invalid identifiers — study it before reading the explanation below.
#include <stdio.h>
int main() {
int 1stRank = 5; // ❌ starts with a digit
int total marks = 90; // ❌ contains a space
float class-avg = 78.5; // ❌ contains a hyphen
int float = 10; // ❌ 'float' is a reserved keyword
printf("%d", 1stRank);
return 0;
}
Line-by-line explanation of what’s wrong:
int 1stRank = 5;— the compiler sees1first and has no idea this is meant to be a variable name; digits can appear in an identifier, but never as the first character.int total marks = 90;— C reads this as two separate tokens,totalandmarks, with no operator connecting them, so it has no idea what you’re trying to declare.float class-avg = 78.5;— the hyphen-is interpreted as the subtraction operator, so the compiler thinks you’re trying to subtractavgfromclass, which makes no sense as a declaration.int float = 10;—floatis one of C’s 32 reserved keywords, so it can never be used as a variable name, no matter the context.
Now here’s the corrected version that actually compiles:
#include <stdio.h>
int main() {
int firstRank = 5; // ✅ starts with a letter
int totalMarks = 90; // ✅ camelCase, no space
float classAvg = 78.5; // ✅ no hyphen
int floatValue = 10; // ✅ not a keyword
printf("Rank: %d\n", firstRank);
printf("Marks: %d\n", totalMarks);
printf("Average: %.1f\n", classAvg);
printf("Value: %d\n", floatValue);
return 0;
}
🖥️ Output:
Rank: 5
Marks: 90
Average: 78.5
Value: 10
✍️ Naming Conventions (Good Practice, Not Strict Rules)
Beyond what the compiler requires, professional programmers follow naming conventions that make code easier to read:
| Convention | Example | Typically used for |
|---|---|---|
| camelCase | totalMarks, studentAge | Variables and functions |
| snake_case | total_marks, student_age | Also common for variables (style preference) |
| ALL_CAPS | MAX_SIZE, PI | Constants (values that never change) |
None of these are enforced by the compiler — but consistent naming makes your code dramatically easier to read and debug, both for you and for anyone else working on it later.
2️⃣ Keywords: The Words That Are “Already Taken”
A keyword (also called a reserved word) is a word that already has a fixed, special meaning to the C compiler. Because the compiler relies on these words to understand your program’s structure, you’re not allowed to use them as identifiers — you can’t name a variable int or a function return.
Standard C defines 32 keywords. Here they all are:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
📚 A Few Keywords You’ll Meet Immediately
| Keyword | Meaning |
|---|---|
int | Declares a variable that stores whole numbers |
float | Declares a variable that stores decimal numbers |
char | Declares a variable that stores a single character |
if / else | Used for decision-making |
for / while | Used for loops (repetition) |
return | Sends a value back from a function |
const | Marks a variable’s value as unchangeable after initialization |
sizeof | Returns the number of bytes a type or variable occupies |
💻 Code Example 2: Keywords in Action
This example uses several keywords together — int, float, if, else, and return — so you can see how each one plays a distinct structural role.
#include <stdio.h>
int main() {
int attendance = 78; // keyword 'int' declares a whole-number variable
if (attendance >= 75) { // keyword 'if' starts a decision
printf("Eligible for exam\n");
} else { // keyword 'else' handles the opposite case
printf("Not eligible\n");
}
printf("Size of int: %zu bytes\n", sizeof(attendance)); // keyword 'sizeof'
return 0; // keyword 'return' ends main() and reports success
}
What each keyword is doing here:
inttells the compiler to reserve enough memory (typically 4 bytes) to store a whole number, and labels that memoryattendance.ifandelsetogether form a decision structure — the compiler checks the condition insideif (...), and runs one block or the other, never both.sizeofis special — it isn’t a function, it’s a compiler keyword that calculates how many bytes a variable or type occupies, entirely at compile time.return 0;hands control back to the operating system and reports that the program finished without errors.
🖥️ Output:
Eligible for exam
Size of int: 4 bytes
⚠️ Common beginner mistake: Writing int float; — this fails to compile because float is a reserved keyword, not a valid variable name. Always keep the keyword list in the back of your mind when naming things.
Think of keywords like reserved seats on a train — they’re permanently allocated for a specific purpose, and you’re not allowed to sit in them no matter how convenient the seat looks.
3️⃣ Variables: Where the Actual Data Lives
A variable is a named location in memory that holds a value — and, true to its name, that value can vary (change) as the program runs. Every variable in C has:
- A name (its identifier)
- A data type (what kind of value it can hold)
- A value (what’s currently stored inside it)
🛠️ Declaring and Initializing a Variable
Declaration tells the compiler a variable exists and what type it is. Initialization gives it a starting value. You can do these separately or in one line.
// Declaration only
int age;
// Declaration + initialization in one step
int age = 20;
// Multiple variables of the same type, declared together
int length, width, height;
// Multiple variables, initialized together
int length = 10, width = 5, height = 3;
📦 Common Data Types for Variables
| Data type | Stores | Typical size | Example declaration |
|---|---|---|---|
int | Whole numbers | 4 bytes | int rollNumber = 42; |
float | Decimal numbers | 4 bytes | float price = 99.50; |
char | A single character | 1 byte | char grade = 'A'; |
double | High-precision decimals | 8 bytes | double pi = 3.14159265; |
💻 Code Example 3: A Complete Student Record Program
Let’s build a small but complete program that declares variables of every basic type and prints them with the correct format specifiers.
#include <stdio.h>
int main() {
int rollNumber = 21;
float height = 5.9;
char grade = 'A';
double gpa = 8.75;
printf("Roll Number: %d\n", rollNumber);
printf("Height: %.1f ft\n", height);
printf("Grade: %c\n", grade);
printf("GPA: %.2lf\n", gpa);
return 0;
}
Line-by-line explanation:
int rollNumber = 21;— reserves 4 bytes of memory, labels itrollNumber, and stores the whole number21in it.float height = 5.9;— reserves memory sized for a decimal number and stores5.9.char grade = 'A';— note the single quotes around'A'— in C, single quotes are used specifically for individual characters, while double quotes are reserved for text strings.double gpa = 8.75;—doubleis used here instead offloatbecause GPA calculations often need more decimal precision.printf("%.1f ft\n", height);— the.1inside%.1ftellsprintfto show exactly one digit after the decimal point.printf("%.2lf\n", gpa);— for adouble, the format specifier is technically written%lf(thelstands for “long”), and.2rounds the output to two decimal places.
🖥️ Output:
Roll Number: 21
Height: 5.9 ft
Grade: A
GPA: 8.75
💡 Format specifier cheat sheet: %d for int, %f for float, %c for char, %lf for double, %s for strings. Using the wrong specifier won’t always stop the program from compiling, but it can print garbage values — always match the specifier to the variable’s actual type.
🔄 Code Example 4: What Happens When a Variable’s Value Changes?
Unlike keywords, which are permanently fixed, a variable’s stored value can be updated any number of times during a program’s execution.
#include <stdio.h>
int main() {
int score = 0; // starts at 0
printf("Initial score: %d\n", score);
score = 10; // value changes
printf("After round 1: %d\n", score);
score = score + 5; // value changes again, based on old value
printf("After round 2: %d\n", score);
score += 20; // shorthand for score = score + 20
printf("After round 3: %d\n", score);
return 0;
}
Line-by-line explanation:
int score = 0;— creates the variable and gives it a starting value of0.score = 10;— the box’s old contents (0) are discarded and replaced with10.score = score + 5;— the right-hand side is evaluated first using the current value ofscore(10), giving15, which is then stored back intoscore.score += 20;— this is a compound assignment operator, shorthand forscore = score + 20. It takes the current value (15), adds20, and stores35back.
🖥️ Output:
Initial score: 0
After round 1: 10
After round 2: 15
After round 3: 35
This is the entire idea behind the word “variable” — the same labeled box gets refilled with a new value each time, and every calculation that reads it uses whatever value is currently stored, not the original one.
💻 Code Example 5: Swapping Two Variables
A classic beginner exercise that really tests whether you understand how variables actually store and overwrite values: swapping the contents of two variables using a third, temporary one.
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
printf("Before swap: a = %d, b = %d\n", a, b);
temp = a; // save a's value before it gets overwritten
a = b; // copy b's value into a
b = temp; // copy the original a (saved in temp) into b
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Why a third variable is necessary: if you tried a = b; b = a; directly, the first line would overwrite a‘s original value before you had a chance to save it — so by the second line, both a and b would end up holding the same value. The temporary variable temp exists purely to hold onto a‘s original value while the swap happens.
🖥️ Output:
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
🔒 Code Example 6: Constants — Variables That Refuse to Change
Sometimes you want a named value that should never change once set — like the value of π, or a fixed tax rate. C provides the const keyword for exactly this.
#include <stdio.h>
int main() {
const float PI = 3.14159;
float radius = 4.0;
float area;
area = PI * radius * radius;
printf("Area of circle: %.2f\n", area);
// PI = 3.14; // ❌ Uncommenting this line causes a compile error!
return 0;
}
Explanation: the const keyword tells the compiler that once PI is initialized, any attempt to reassign it should be treated as an error — not a warning, an actual compile failure. This is useful for values that represent fixed facts (like π) or safety-critical settings that should never be accidentally modified elsewhere in the code.
🖥️ Output:
Area of circle: 50.27
💡 Naming convention reminder: Notice PI is written in ALL_CAPS — this is the standard convention for constants, making it instantly recognizable as a value that won’t change, just by looking at its name.
🌍 Real-World Analogy: A School Admission Form
Think about filling out a school admission form:
- Each field on the form (Name, Age, Grade) is like a variable — a labeled space waiting for a value
- The field label itself (“Age:”) is the identifier
- Certain words are off-limits as field labels because the form itself already uses them for its own structure (like “Form,” “Section,” or “Date”) — this mirrors keywords
- Filling in “20” for age today and updating it to “21” next year is exactly what happens when a variable’s value changes
- A field like “Date of Birth,” which is filled in once and never edited again, behaves like a constant
🚫 Common Mistakes Beginners Make
| Mistake | Why it fails |
|---|---|
int 2ndValue; | Identifier starts with a digit |
int char; | char is a reserved keyword |
int my value; | Identifier contains a space |
Using Total and total interchangeably, expecting them to be the same variable | C is case-sensitive — these are two distinct identifiers |
| Using a variable before declaring it | The compiler doesn’t know the variable’s type or size yet |
float price = 10.5 (missing semicolon) | The compiler can’t tell where the statement ends |
Reassigning a const variable | Constants are locked after initialization — reassignment is a compile error |
Using %d to print a float value | Mismatched format specifiers print garbage or incorrect values |
💡 Debugging tip: If your compiler throws an error mentioning a keyword you didn’t expect (like "expected identifier before 'int'"), check whether you’ve accidentally tried to use a keyword as a variable name.
🧩 Quick Reference Table
| Term | Definition | Example |
|---|---|---|
| Identifier | A user-defined name for a variable, function, etc. | totalMarks |
| Keyword | A reserved word with a fixed compiler meaning | int, for, return |
| Variable | A named, typed storage location whose value can change | int age = 20; |
| Constant | A variable whose value is locked after initialization | const float PI = 3.14; |
| Declaration | Telling the compiler a variable exists and its type | int age; |
| Initialization | Giving a variable its first value | age = 20; |
| Compound assignment | Shorthand for updating a variable based on its own value | score += 5; |
🎓 Code-Tracing & Practice Exercises
Exercise 1: Valid or Invalid?
For each of the following, decide whether it’s a valid C identifier — and if not, say why.
a) totalPrice
b) 3rdAttempt
c) grade_A
d) return
e) _temp
f) student#1
(Answers: a) valid — b) invalid, starts with a digit — c) valid — d) invalid, it’s a keyword — e) valid — f) invalid, contains a special symbol.)
Exercise 2: Predict the Output
#include <stdio.h>
int main() {
int Marks = 90;
int marks = 45;
printf("%d %d", Marks, marks);
return 0;
}
(Answer: it prints 90 45 — because C is case-sensitive, Marks and marks are two entirely separate variables.)
Exercise 3: Trace the Variable Changes
#include <stdio.h>
int main() {
int x = 4;
int y = x + 2;
x = y * 2;
y = x - y;
printf("x = %d, y = %d", x, y);
return 0;
}
Trace through each line by hand, writing down the value of x and y after every statement, before checking the answer.
(Answer: y = 4 + 2 = 6, then x = 6 * 2 = 12, then y = 12 - 6 = 6. Final output: x = 12, y = 6.)
Exercise 4: Short Coding Exercise
Declare three variables to store a student’s name’s first initial (as a char), their total marks (as an int), and their percentage (as a float). Initialize them with sample values and print all three using a single printf() statement. Then declare a fourth variable, attempts, and use a compound assignment operator to increase it by 1, simulating a re-attempt.
✍️ Try writing this one yourself before checking a solution — this is exactly the kind of short coding exercise this lesson is building toward.
❓ Frequently Asked Questions
Q: Can an identifier be exactly the same as a keyword, just with different capitalization — like Int instead of int?
Yes — because C is case-sensitive, Int is not the same as the keyword int, so it’s technically a valid identifier. That said, using it is a bad idea — it’s confusing for anyone reading your code.
Q: Is there a maximum length for an identifier?
Older C standards guaranteed only the first 31 characters were significant, but modern compilers support much longer names. Regardless of the technical limit, keep names short but descriptive for readability.
Q: What’s the difference between declaring and initializing a variable?
Declaring just reserves memory and tells the compiler the type (int age;). Initializing assigns it a starting value, either at the same time (int age = 20;) or afterward (age = 20;).
Q: Can I use an underscore as the very first character of a variable name?
Yes, it’s legal — but in practice, identifiers starting with an underscore are often reserved by convention for system-level or library code, so beginners are usually advised to start with a letter instead.
Q: What actually happens in memory when I declare a variable?
The compiler reserves a block of memory sized according to the data type (4 bytes for int, 1 byte for char, and so on), and internally associates your identifier with that memory address. Every time you use the variable’s name afterward, the compiler translates it into a reference to that exact memory location.
Q: Why does swapping two variables need a third, temporary one?
Because assignment always overwrites the previous value. Without a temporary variable to hold onto the original value of the first variable, that value is lost the moment you copy the second variable’s value into it — see Code Example 5 above for a full trace.
✅ Key Takeaways
- An identifier is a name you create for a variable, function, or other program element — it must start with a letter or underscore and contain no spaces or special symbols.
- A keyword is a word already reserved by C for a fixed purpose — there are 32 of them, and none can be used as an identifier.
- C is case-sensitive —
Total,total, andTOTALare three different identifiers. - A variable is a named, typed storage location whose stored value can change throughout the program, while a constant (declared with
const) locks that value after initialization. - Format specifiers (
%d,%f,%c,%lf) must match a variable’s data type when printing, or output can come out wrong. - Compound assignment operators like
+=are shorthand for updating a variable based on its own current value. - Following consistent naming conventions (camelCase, snake_case, or ALL_CAPS for constants) isn’t required by the compiler, but makes real-world code far easier to read.
🚀 Next up: Now that you can name, declare, initialize, and update variables correctly, we’ll explore C’s data types in more depth — how much memory each one uses, their ranges, and how to choose the right type for the job.