C Variable

A C variable is a named storage location in memory that holds a value of a specific data type (such as integer, float, or character). You can use variables to store and manipulate data in your C programs.

About C Variable

Declaration: A variable in C must be declared before it is used. The declaration includes the variable’s name and its data type.


int age

Initialization: A variable can be initialized with a value when it is declared, or its value can be set later in the program.


int age = 35;

Example:


#include <stdio.h>

int main() {
    int age = 35;
    printf("John age is %d", age);
    return 0;  // Exit the program successfully
}

Note: %d is used to print integers value.

Output:

John age is 35

Scope of Variable

A variable’s scope refers to where it can be accessed. A variable can be local (inside a function) or global (outside any function).

Local Variables: These are variables declared inside a function or block. Their scope is limited to that function or block.

Global Variables: These are variables declared outside of any function. They can be accessed by any function in the program.

Example:


#include <stdio.h>

int globalVar = 45;
int main() {
    int localVar = 35;
    printf("local variable %d\n", localVar);
    printf("global variable %d", globalVar);
    return 0;  // Exit the program successfully
}

Output:

local variable 35
global variable 45

Variable Naming Rules

A variable name in C must start with a letter or an underscore and can be followed by letters, digits, or underscores. It is case-sensitive, so age and Age would be different variables.