In this post, we will learn about variables in c. We will go through different rules while naming variables in c, some examples of valid or invalid variable names in c, local variable and global variable in c etc.
1. Variables in C
- C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
- A variable is a data name that may be used to store a data value.
- It remains unchanged during the execution of program.
- To indicate storage area, each variable should be given a unique name.
- Variable names are case sensitive. Like num, Num, NUM these all three are different variable names.
Some examples of such names are –
Average, Height, Total, Counter_1, Class_10 |
Rules for Constructing Variable Name:
- 1. Characters Allowed:
- Underscore(_)
- Capital Letters ( A – Z )
- Small Letters ( a – z )
- Digits ( 0 – 9 )
- Blanks & Commas are not allowed.
- No Special Symbols other than underscore(_) are allowed.
- First Character should be alphabet or Underscore.
- Variable name should not be reserved word.
Some valid variable’s name in C –
number, number1, _number, NUM_1, num_, num_of_students |
Some invalid variable’s name in C –
Invalid Name |
Reason for Invalid Name |
num ber |
Space between `m` and `b` |
1number |
Start with number |
1_num |
Start with number |
num@ |
Having special character |
int |
Reserved word |
num& |
Having special character |
2. Local Variable in C
- A local variable in C is declared inside a function.
- It is visible only inside their function, only statements inside function can access that local variable.
- Local variables is declared when control enters a function and destroyed, when control exits from function.
Program to understand the concept of Local variable in C
printf (“Sum = %d”, add(a, b)); |
OUTPUT
3. Global Variable in C
- A variable that is declared outside of all functions.
- It holds their values between function calls and throughout the program execution.
Program to understand the concept of Global Variable in C
printf( "\n Global Variables: a=%d b=%d" , a,b); |
printf( "\n Local Variable of main function: x = %d" , x); |
printf( "\n Global Variables: a = %d b = %d" , a,b); |
printf( "\n Local Variable of demo function: p = %d" , p); |
Output
Global Variables: a = 10 b = 20 |
Local Variable of main function: x = 50 |
Global Variables: a = 10 b = 20 |
Local Variable of demo function: p = 100 |