Skip to main content

Variables in C ๐Ÿ“ฆ

Mentor's Note: Think of a variable as a labeled storage box in a warehouse. You can put things in, take things out, or replace them, but the box label tells you what type of item belongs inside! ๐Ÿ’ก

๐Ÿ“š Educational Content: This tutorial is designed to align with GSEB Std 10/12, CBSE Computer Science, and BCA Sem 1 syllabus standards.

What You'll Learn

By the end of this tutorial, you'll know:

  • What variables are and how the "labeled box" analogy works.
  • The difference between declaring and initializing variables in C.
  • The strict naming rules for variables in C (board exam favorite).
  • How to print variable values using printf format specifiers.
  • The difference between local and global variables.

๐ŸŒŸ The Scenario: The Post Office Mailboxesโ€‹

Imagine you walk into a Post Office containing thousands of small mailboxes. To store letters or packages, each mailbox has two things:

  1. A Label: A unique name written on the outside (like "Box 14", "Raj_Mail", or "Rent_Due") so you know which box is which.
  2. A Size Limit: Some boxes are tiny slot-like mailboxes for letters, while others are large lockers for packages. You cannot put a large package into a letter slot.

To store information in a computer, the computer does the exact same thing. It reserves a small portion of its memory (a mailbox), gives it a name (a label), and restricts what kind of data can fit inside it based on its type.

In programming:

  • The Mailbox is a Variable.
  • The Label is the Variable Name (Identifier).
  • The Contents of the box is the Value stored in the variable.
  • The Box Type is the Data Type (like integer or character).

๐Ÿ“– Concept Explanationโ€‹

What is a Variable?โ€‹

A variable is a named location in a computer's memory used to store data that can be changed during program execution.

Declaration vs Initializationโ€‹

Before you can use a variable in C, you must tell the computer about it. This is a two-step process (though it can be done in a single line):

  1. Declaration: Telling the compiler the name of the variable and what kind of data it will hold. This reserves memory space.
    int age; // Declares an integer variable named 'age'
  2. Initialization: Giving an initial value to the declared variable.
    age = 16; // Initializes the variable 'age' with the value 16

You can combine both steps in a single line:

int age = 16; // Declaration and initialization

Strict Variable Naming Rulesโ€‹

In C, you cannot name variables whatever you want. The rules are strict and frequently tested in board exams:

  1. First character: Must be a letter (A-Z, a-z) or an underscore (_). It cannot start with a number.
    • โœ… int age; | โœ… int _temp;
    • โŒ int 32age;
  2. Allowed characters: Can only contain letters, numbers, and underscores. No spaces or special characters (like $, @, #, -) are allowed.
    • โœ… int roll_number;
    • โŒ int roll number; | โŒ int roll-number;
  3. No Keywords: You cannot use C keywords (like int, float, return, void, if) as variable names.
    • โŒ int return;
  4. Case Sensitivity: C is case-sensitive. age, Age, and AGE are treated as three completely different variables.

๐Ÿง  Variable Scope: Local vs Globalโ€‹

The scope of a variable determines where in your code that variable can be accessed and modified.

1. Local Variablesโ€‹

  • Where: Declared inside a function block { ... }.
  • Access: Only accessible within the function they are declared in. Other functions don't even know they exist.
  • Lifetime: Created when the function starts and destroyed when the function ends.

2. Global Variablesโ€‹

  • Where: Declared outside all functions (usually at the very top of the file, below #include).
  • Access: Accessible by any function anywhere in the program.
  • Lifetime: Exists as long as the program is running.

๐Ÿ’ป Working Example: Variable Scope and Typesโ€‹

Here is a complete C program demonstrating variable declaration, initialization, format specifiers, and scopes.

#include <stdio.h>

// Global variable (Accessible by all functions)
int globalCount = 50;

void displayAnother() {
// Local variable to displayAnother
int localVal = 5;
printf("displayAnother -> localVal: %d, globalCount: %d\n", localVal, globalCount);
}

int main() {
// Local variables to main
int age = 16;
float marks = 94.5f;
char grade = 'A';

printf("main -> age: %d\n", age);
printf("main -> marks: %.1f\n", marks);
printf("main -> grade: %c\n", grade);
printf("main -> globalCount: %d\n", globalCount);

displayAnother();

return 0;
}

// Output:
// main -> age: 16
// main -> marks: 94.5
// main -> grade: A
// main -> globalCount: 50
// displayAnother -> localVal: 5, globalCount: 50

๐Ÿ“Š Sample Dry Runโ€‹

Let's trace the variable values step-by-step through execution:

StepLine of Code ExecutedVariable NameTypeValue in MemoryDescription
1int globalCount = 50;globalCountint (Global)50Allocated in global data segment.
2int age = 16;ageint (Local)16Allocated on main stack frame.
3float marks = 94.5f;marksfloat (Local)94.5Allocated on main stack frame.
4char grade = 'A';gradechar (Local)'A' (ASCII 65)Allocated on main stack frame.
5displayAnother();localValint (Local)5Created on displayAnother stack frame.
6Function exitslocalValint(Destroyed)Local variable space is freed.

๐Ÿงช Interactive Elementsโ€‹

Try It Yourselfโ€‹

Hands-on Exercise: Scope Violation

Task: Try adding printf("%d", localVal); inside the main() function of the code above and compile it. See what error the compiler outputs.

Hint: Since localVal is local to displayAnother(), compiling this will result in an error: 'localVal' undeclared in main.

Quick Quizโ€‹

Quick Quiz: Valid Identifiers

Which of the following is a valid variable name in C?

  • A) 2nd_number
  • B) float
  • C) total_sum
  • D) price$

Explanation:

  • 2nd_number is invalid because it starts with a number.
  • float is invalid because it is a reserved keyword.
  • price$ is invalid because it contains the special character $.
  • total_sum is valid because it starts with a letter and contains only letters and underscores.

๐Ÿ“‰ Complexity Analysisโ€‹

  • Time Complexity:
    • Variable Initialization: $O(1)$ constant time.
    • Variable Access: $O(1)$ constant time lookup via memory address.
  • Space Complexity:
    • Memory allocation: $O(1)$ auxiliary space. The program allocates a fixed number of bytes in memory (e.g. 4 bytes for int, 4 bytes for float, 1 byte for char).

๐ŸŽฏ Practice Problemsโ€‹

Easy Level ๐ŸŸขโ€‹

  1. Write a program to declare three variables: an integer for roll number, a float for temperature, and a character for section. Assign values and print them.
  2. Identify which of these variable names are invalid and explain why:
    • student age
    • _average_mark
    • double
    • num_1

Medium Level ๐ŸŸกโ€‹

  1. Write a program with a global variable named score. Modify the value of score inside main() and print it. Then call a function printScore() to verify that the modified value is accessible there too.

Hard Level ๐Ÿ”ดโ€‹

  1. Write a program where a local variable in main has the exact same name as a global variable. Assign different values to both. Print the variable inside main and explain which value gets printed and why (shadowing/masking concept).

โ“ Frequently Asked Questionsโ€‹

Details

Q: What happens if I declare a variable but do not initialize it? In C, if you declare a local variable but do not give it a value, it will contain a garbage value (whatever random bits of data were already left behind in that memory location). Always initialize your variables before reading them to avoid unpredictable bugs!

Details

Q: Why is C called a "statically typed" language? "Statically typed" means that the compiler must know the data type of every variable at compilation time. Once you declare a variable as an int, you cannot store a string in it later, and you cannot change its type during runtime (unlike Python or JavaScript).

Details

Q: Why should we limit the use of global variables? Global variables can be read and modified by any part of the program. If you have a bug where a global variable has the wrong value, you have to check every single function to find who changed it. Keeping variables local makes code modular and much easier to debug.


๐Ÿ“š Best Practices & Common Mistakesโ€‹

โœ… Best Practicesโ€‹

  • Always initialize local variables: Initialize them during declaration (e.g. int count = 0;) to prevent reading garbage values.
  • Use camelCase or snake_case: Choose one naming convention and stick to it (e.g., studentAge or student_age).
  • Use meaningful names: Name variables for what they represent (use averageMarks instead of just x).

โŒ Common Mistakes โš ๏ธโ€‹

  • Declaring variables inside loops repeatedly: Declaring variables inside a loop block can confuse beginners about the variable's lifetime.
  • Trying to use a variable before declaring it: Writing count = 10; int count; instead of declaring it first.
  • Using a keyword: Declaring int char; or int default;.

โœ… Summaryโ€‹

In this tutorial, you've learned:

  • โœ… Variables are named boxes in memory that store values.
  • โœ… Declaring reserves memory; initializing assigns the first value.
  • โœ… Variable names can contain letters, numbers, and underscores, but must start with a letter or _.
  • โœ… Local variables exist inside functions; global variables exist across the whole program.
  • โœ… C is case-sensitive, meaning age and Age are separate variables.

๐Ÿ’ก Pro Tip: Use the const keyword before your variable type if you want to create a variable whose value cannot be changed after initialization (e.g., const float PI = 3.14;).


๐Ÿ“š Further Readingโ€‹

Continue your learning path:

Go deeper:


---

๐Ÿ“ Visit Us

๐Ÿซ VD Computer Tuition Surat

VD Computer Tuition
๐Ÿ“ Address
2/66 Faram Street, Rustompura
Surat โ€“ 395002, Gujarat, India
๐Ÿ“ž Phone / WhatsApp
+91 84604 41384
๐ŸŒ Website

Computer Classes & Tuition โ€” Areas We Serve in Surat

Adajanโ€ขAlthanโ€ขAmroliโ€ขAthwaโ€ขAthwalinesโ€ขBhagalโ€ขBhatarโ€ขBhestanโ€ขCanal Roadโ€ขChowkโ€ขCitylightโ€ขDumasโ€ขGaurav Pathโ€ขGhod Dod Roadโ€ขHaziraโ€ขJahangirpuraโ€ขKamrejโ€ขKapodraโ€ขKatargamโ€ขLimbayatโ€ขMagdallaโ€ขMajura Gateโ€ขMota Varachhaโ€ขNanpuraโ€ขNew Citylightโ€ขOlpadโ€ขPalโ€ขPandesaraโ€ขParle Pointโ€ขPiplodโ€ขPunaโ€ขRanderโ€ขRing Roadโ€ขRustampuraโ€ขSachinโ€ขSalabatpuraโ€ขSarthanaโ€ขSosyo Circleโ€ขUdhnaโ€ขVarachhaโ€ขVed Roadโ€ขVesuโ€ขVIP Road
๐Ÿ“ž Call Sir๐Ÿ’ฌ WhatsApp Sir