Variables in C 1
Variables in C 1
Topperworld.in
Variables in C
©Topperworld
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the
variable.
Here,
• data_type: Type of data that a variable can store.
• variable_name: Name of the variable given by the user.
• value: value assigned to the variable by the user.
©Topperworld
C Programming
➔ C Variable Declaration
➔ C Variable Definition
Example:
int var;
char var2;
➔ C Variable Initialization
Example:
int var; // variable definition
var = 10; // initialization
or
int var = 10; // variable declaration and
definition
©Topperworld
C Programming
Types of Variables
The C variables can be classified into the following types:
➢ Local Variables
➢ Global Variables
➢ Static Variables
➢ Automatic Variables
➢ Extern Variables
➢ Register Variables
➔ Local Variables in C
➔ Global Variables in C
©Topperworld
C Programming
➔ Static Variables in C
➔ Automatic Variable in C
• All the local variables are automatic variables by default. They are also
known as auto variables.
• Their scope is local and their lifetime is till the end of the block. If we need,
we can use the auto keyword to define the auto variables.
• The default value of the auto variables is a garbage value.
➔ External Variables in C
• External variables in C can be shared between multiple C files. We can
declare an external variable using the extern keyword.
• Their scope is global and they exist between multiple C files.
➔ Register Variables in C
• Register variables in C are those variables that are stored in the CPU
register instead of the conventional storage place like RAM.
• Their scope is local and exists till the end of the block or a function.
• These variables are declared using the register keyword.
• The default value of register variables is a garbage value.
©Topperworld
C Programming
➔ Example:
// C Program to Demonstrate Various types of variable
#include <stdio.h>
// Global variable
int globalVar = 10;
int main() {
// Automatic (default) variable
int autoVar = 5;
// Local variable
int localVar = 20;
// Static variable
static int staticVar = 15;
return 0;
}
Output:
Global variable: 10
Automatic variable: 5
Local variable: 20
Static variable: 15
Register variable: 25 ©Topperworld
C Programming
➔ Constant Variable in C
• Till now we have only seen the variables whose values can be modified
any number of times.
• C language also provides us a way to make the value of a variable
immutable. We can do that by defining the variable as constant.
• A constant variable in C is a read-only variable whose value cannot be
modified once it is defined. We can declare a constant variable using
the const keyword.
Example:
int main()
{
int not_constant;
// changing values
not_constant = 40;
constant = 22;
return 0;
}
Output:
Constant = 22
©Topperworld