A variable is a named location in memory that holds a value. It is used to store data value or information.
The value or data of the variable can be changed during the execution of the program. Variable has its size, range, name (identifier) and address. The size and range of the variable depend and specify by its data type.
i. Declaration of Variables: Before using a variable, you need to declare it by specifying its type and name.
Syntax -
type variable_name;
Example -
int age; // declares an integer variable named 'age'
float temperature; // declares a floating-point variable named 'temperature'
char grade; // declares a character variable named 'grade'
ii. Initialization of Variables: Variables can be initialized at the time of declaration by assigning an initial value to them. For example:
Syntax -
type variable_name = 50;
Example -
int count = 0; // initializes an integer variable 'count' with the value 0 float pi = 3.14; // initializes a floating-point variable 'pi' with the value 3.14 char letter = 'A'; // initializes a character variable 'letter' with the value 'A'
In C, variables can have either global or local scope.
• Global variables are declared outside of any function and can be accessed from anywhere in the program.
• Local variables are declared inside functions or blocks and can only be accessed within their respective scope.
iii. Naming rules of Variables:
• They must start with either an underscore (_) or a letter (a-z, A-Z).
• After the first character, they can contain letters, digits (0-9), or underscores.
• Variable names are case-sensitive.
• No commas or blank spaces are allowed.
• Variables name can't start with a number.
• Variables can't be a reserved keywords.
• Variables can't have same names.
iv. Modifying variables: Once a variable is declared, you can assign new values to it using the assignment operator (=).
For example:
age = 25; // assigns the value 25 to the variable 'age'
temperature = 98.6; // assigns the value 98.6 to the variable 'temperature'
grade = 'B'; // assigns the character 'B' to the variable 'grade'
v. Manipulating variables: Variables can be manipulated using various operators, such as arithmetic operators (+, -, *, /), assignment operators (+=, -=, *=, /=), and more.