Declaration of Variables in C

In C programming, variables are used to store data that can be modified during program execution. Before using a variable, it must be declared. This process involves specifying a data type and a variable name. Declaring variables helps the compiler allocate memory for the data and understand how the variable will be used.

Syntax for Declaring Variables

The general syntax for declaring a variable in C is:
data_type variable_name;

For example:

Rules for Naming Variables

Types of Variable Declarations

There are different ways to declare variables in C:

1. Single Variable Declaration

Example:
int score;

2. Multiple Variable Declaration

Example:
int x, y, z;

3. Initialized Declaration

Example:
int count = 10;

Example: Declaring and Initializing Variables


#include <stdio.h>
int main() {
    int a = 5, b = 10, c; // Multiple declaration with initialization
    c = a + b; // Adding a and b
    printf("Sum of a and b: %d\n", c);
    
    float pi = 3.14, radius = 2.5, area;
    area = pi * radius * radius; // Calculating area of a circle
    printf("Area of the circle: %.2f\n", area);
    
    char grade = 'A'; // Declaring a character variable
    printf("Student's grade: %c\n", grade);

    return 0;
}

Output

Sum of a and b: 15 Area of the circle: 19.63 Student's grade: A

Explanation of Code Example:

Memory Allocation of Variables

When you declare a variable in C, the compiler allocates a specific amount of memory based on the data type:

Data Type Memory (bytes) Range
int 2 or 4 -32,768 to 32,767 (for 2 bytes)
float 4 1.2E-38 to 3.4E+38
char 1 -128 to 127
double 8 2.3E-308 to 1.7E+308

Best Practices for Variable Declaration

Common Errors in Variable Declaration