View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

All About Variables in C: Syntax, Types & Examples

Updated on 06/05/20253,336 Views

When you start writing a program in C, managing data efficiently becomes essential. You’ll find that Variables in C play a central role in storing, processing, and manipulating values throughout your code. Whether you’re solving simple problems or building complex systems, they act as the building blocks for handling dynamic information inside a program.

In every C program, understanding where and how to store values is key to controlling logic and operations. Variables make it possible to assign, update, and retrieve data as your program runs. By learning how to use them effectively, you gain control over memory, scope, and data flow—setting a strong foundation for reliable and optimized coding. 

Pursue our Software Engineering courses to get hands-on experience!

What Are Variables in C?

Variables in C are user-defined names that act as placeholders for storing different kinds of data in a program. They allow you to store values temporarily in the system’s memory and reuse or modify them as the program executes. Every variable reserves a specific memory location to hold a value.

When you declare a variable, you also specify the type of data it can store, such as integers, floating-point numbers, or characters. This type determines the amount of memory allocated and the kind of operations you can perform on the variable. Understanding variables is crucial for writing efficient and error-free code.

Take your skills to the next level with these top programs:

Syntax of Variable in C

The syntax for declaring a variable in C is straightforward. You need to specify the data type, followed by the variable name and a semicolon. Optionally, you can initialize it with a value at the time of declaration.

data_type variable_name;

Here’s an example:

int age;

float marks;

char grade;

In this example, age is an integer variable, marks is a floating-point variable, and grade is a character variable.

You can also initialize a variable during declaration:

int age = 25;

float marks = 89.5;

char grade = 'A';

Explanation:

  • int age = 25; creates an integer variable age and assigns it the value 25.
  • float marks = 89.5; creates a float variable marks with value 89.5.
  • char grade = 'A'; creates a character variable grade with value A.

Rules for Naming a Variable in C

When naming a variable in C, you must follow specific rules:

  1. The name must begin with a letter (A-Z or a-z) or an underscore (_).
  2. It can contain letters, digits (0-9), or underscores.
  3. No spaces or special characters (except underscore) are allowed.
  4. Reserved keywords cannot be used as variable names.
  5. Variable names are case-sensitive.

Here are valid examples:

int total_marks;

float percentage1;

char _grade;

And here are invalid examples:

int 1total;    // Invalid: starts with a digit

float %marks;   // Invalid: contains a special character

char class;     // Invalid: 'class' is a keyword

Explanation: Variable names should be clear, meaningful, and follow the rules to avoid compilation errors.

Declaration of Variables in C

Declaring a variable in C tells the compiler to allocate memory for it with a specific data type. The general form is:

data_type variable_name;

You can declare multiple variables of the same type in one line:

int x, y, z;

float a, b;

Variables must be declared before they are used in the program.

Example:

#include <stdio.h>
int main() {
    int age;
    float marks;
    char grade;
    printf("Variables declared successfully.\n");
    return 0;
}

Output:

Variables declared successfully.

Explanation: This program declares an integer, a float, and a character variable. It prints a message to confirm the declaration.

Initialization of Variables in C

Initialization assigns an initial value to a variable at the time of declaration. This ensures the variable holds a known value before use.

data_type variable_name = value;

Example:

#include <stdio.h>
int main() {
    int age = 20;
    float marks = 85.5;
    char grade = 'A';
    printf("Age: %d\nMarks: %.2f\nGrade: %c\n", age, marks, grade);
    return 0;
}

Output:

Age: 20
Marks: 85.50
Grade: A

Explanation: The variables age, marks, and grade are initialized with values and printed using printf().

Types of Variables in C

Each variable in C is associated with a specific data type—learn more in this detailed article on data types in C. Variables in C are categorized based on their scope, storage, and lifetime. The main types are local, global, static, extern, and register variables. Each type serves a specific purpose.

Local Variable in C

A local variable is declared inside a function or block and is accessible only within that function or block.

Example:

#include <stdio.h>
void display() {
    int num = 10;
    printf("Local variable num = %d\n", num);
}
int main() {
    display();
    // printf("%d", num); // Error: num not accessible here
    return 0;
}

Output:

Local variable num = 10

Explanation: num is a local variable declared inside display(). It is not accessible outside the function.

Global Variable in C

A global variable is declared outside all functions and can be accessed by any function in the program.

Example:

#include <stdio.h>
int count = 100; // Global variable
void display() {
    printf("Count = %d\n", count);
}
int main() {
    display();
    printf("Count in main = %d\n", count);
    return 0;
}

Output:

Count = 100
Count in main = 100

Explanation: count is a global variable accessible in both display() and main().

Static Variable in C

A static variable retains its value across function calls and is initialized only once.

Example:

#include <stdio.h>
void counter() {
    static int num = 0;
    num++;
    printf("Num = %d\n", num);
}
int main() {
    counter();
    counter();
    counter();
    return 0;
}

Output:

Num = 1
Num = 2
Num = 3

Explanation: num keeps its value between calls to counter(). It increments with each call.

Extern Variable in C

An extern variable is declared using extern keyword to access a global variable defined in another file or scope.

Example:

#include <stdio.h>
int num = 10; // Global variable
void display();
int main() {
    extern int num;
    display();
    printf("Num in main = %d\n", num);
    return 0;
}
void display() {
    printf("Num in display = %d\n", num);
}

Output:

Num in display = 10
Num in main = 10

Explanation: extern allows accessing the global num in main() even if declared elsewhere.

Register Variable in C

A register variable requests the compiler to store it in a CPU register for faster access.

Example:

#include <stdio.h>
int main() {
    register int i;
    for (i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    return 0;
}

Output:

1 2 3 4 5

Explanation: i is declared as a register variable. It works like a normal variable but with a hint for faster access.

Remember, variable names follow the same rules as identifiers. Explore identifiers in C.

Classification of Variables in C

Variables can also be classified based on scope, lifetime, and storage class.

  1. Scope: Determines where a variable is accessible (local or global).
  2. Lifetime: Defines how long the variable exists in memory.
  3. Storage Class: Specifies how the variable is stored and initialized (auto, static, extern, register).

Understanding classification helps in writing memory-efficient and maintainable code.

Example of Classification of Variable in C

Here’s a program showing local, global, and static variables:

#include <stdio.h>
int globalVar = 5; // Global variable
void function() {
    static int staticVar = 1; // Static variable
    int localVar = 2; // Local variable
    printf("Global: %d, Static: %d, Local: %d\n", globalVar, staticVar, localVar);
    staticVar++;
}
int main() {
    function();
    function();
    return 0;
}

Output:

Global: 5, Static: 1, Local: 2
Global: 5, Static: 2, Local: 2

Explanation: globalVar is accessible in both function() and main(). staticVar retains its value between calls. localVar resets with each call.

C variables can have different storage classes—explore this comprehensive guide on storage classes in C.

Constants in C

Constants in C are fixed values that cannot be changed during program execution. They improve readability and safety by preventing unintended modification. You can define constants using #define or the const keyword.

Example of Constant in C

#include <stdio.h>
#define PI 3.1415
int main() {
    const int DAYS = 7;
    printf("PI: %.4f\n", PI);
    printf("Days in a week: %d\n", DAYS);
    return 0;
}

Output:

PI: 3.1415
Days in a week: 7

Explanation: PI is defined as a macro constant. DAYS is a constant integer using const. Neither can be modified.

Example of Variable in C

Here’s a simple program using different types of variables:

#include <stdio.h>

int globalVar = 100; // Global variable
int main() {
    int localVar = 50; // Local variable
    static int staticVar = 20; // Static variable
    printf("Global: %d\nLocal: %d\nStatic: %d\n", globalVar, localVar, staticVar);
    return 0;
}

Output:

Global: 100
Local: 50
Static: 20

Explanation: The program demonstrates global, local, and static variables by printing their values.

Variables often work with operators—this article on C operators gives a solid overview.

Conclusion

Variables in C are essential for storing and managing data within a program. By understanding different types, scopes, and storage classes, you can write clearer, more optimized code. Using constants alongside variables ensures better control and safety in programming. Mastering these concepts lays the groundwork for more advanced C programming techniques.

FAQs

1. What is a variable in C with an example?

A variable in C stores data in a named memory location. For example, int age = 25; declares an integer variable age and initializes it with 25. Variables let you store, update, and use data in a C program.

2. What is the difference between variable declaration and definition in C?

Variable declaration tells the compiler about a variable’s name and type without allocating storage. Definition allocates memory. For example, extern int x; is a declaration, while int x = 10; is a definition and initialization.

3. Can we declare multiple variables in a single line in C?

Yes, you can declare multiple variables of the same data type in one line by separating them with commas. For example, int a, b, c; declares three integer variables: a, b, and c, saving space and improving readability.

4. What is the default value of variables in C?

In C, local variables have garbage values by default because they are not automatically initialized. However, global and static variables are automatically initialized to zero if not explicitly assigned a value at declaration.

5. Why should we initialize variables in C?

You should initialize variables in C to avoid using undefined or garbage values, which can lead to unpredictable program behavior. Initialization assigns a known starting value, improving program correctness, stability, and debugging effectiveness.

6. What is the scope of a variable inside a loop in C?

A variable declared inside a loop in C is local to that loop’s block. It exists only during each iteration and cannot be accessed outside the loop. For example, for (int i = 0; i < 5; i++) keeps i local.

7. What is the lifetime of a static variable in C?

A static variable in C retains its value and exists for the entire program execution, even though it has local scope. It is initialized only once. Each time the function is called, the static variable keeps its last updated value.

8. What is the difference between local and global variables in C?

A local variable is declared inside a function or block and accessible only there. A global variable is declared outside all functions and accessible throughout the entire program by any function or block needing it.

9. Can you change a constant variable in C?

No, a constant variable declared using const or #define cannot be modified after initialization. Attempting to change its value will result in a compile-time error, ensuring data integrity and protecting critical program constants.

10. What is a register variable in C used for?

A register variable in C hints the compiler to store the variable in a CPU register instead of RAM for faster access. It is useful for frequently accessed variables like counters, though modern compilers optimize register use automatically.

11. How does an extern variable work across multiple files in C?

An extern variable allows sharing a global variable across multiple C files. You declare the variable with extern in other files while defining it in one file, enabling cross-file access without redefining memory allocation.

12. Are variable names case-sensitive in C?

Yes, variable names in C are case-sensitive. For example, int age; and int Age; are treated as two different variables. It’s essential to consistently use the correct case to avoid errors and confusion in your code.

13. Can you use special characters in variable names in C?

No, you cannot use special characters like @, #, $, etc., in variable names in C. Only letters (A–Z, a–z), digits (0–9), and underscores _ are allowed, and names cannot start with a digit.

14. Why do we use storage classes with variables in C?

Storage classes in C (auto, static, extern, register) define a variable’s scope, lifetime, and storage location. Choosing the right storage class helps control memory usage, access permissions, and data persistence across function calls in a program.

15. What are the best practices for naming variables in C?

Use meaningful, descriptive names that reflect the variable’s purpose, like totalMarks or studentAge. Avoid abbreviations or single letters unless used in loops. Always follow C naming rules and avoid reserved keywords to ensure clear, error-free code.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.