Declaration and Assignment of Variables in C
In C, variables must be declared before they can be used. A variable declaration specifies the data type and name of the variable, while assigning a value stores data in the variable.
1. Declaring a Variable
Syntax:
- data_type: The type of data the variable will store (e.g.,
int
,float
,char
). - variable_name: A unique name for the variable.
Example:
2. Assigning a Value to a Variable
Syntax:
- variable_name: The name of the declared variable.
- value: The data you want to assign to the variable.
Example:
3. Declaring and Assigning a Variable in One Step
You can declare and assign a variable in the same statement.
Syntax:
Example:
4. Declaring Multiple Variables
You can declare multiple variables of the same data type in a single statement.
Syntax:
Example:
You can also initialize multiple variables during declaration:
Rules for Declaring Variables
- Variable names must start with a letter or underscore (
_
). - Variable names can only contain letters, digits, and underscores.
- Keywords cannot be used as variable names (e.g.,
int
,float
). - Variable names are case-sensitive (
age
andAge
are different).
Examples of Variable Declaration and Assignment
#include <stdio.h>
int main() {
// Declaration
int age; // Declares an integer variable
float height; // Declares a floating-point variable
char grade; // Declares a character variable
// Assigning values
age = 25; // Assigns value to ‘age’
height = 5.9; // Assigns value to ‘height’
grade = ‘A’; // Assigns value to ‘grade’
// Declaration and Assignment in one step
int score = 95;
float weight = 70.5;
char initial = ‘S’;
// Print the variables
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);
printf(“Grade: %c\n”, grade);
printf(“Score: %d\n”, score);
printf(“Weight: %.1f\n”, weight);
printf(“Initial: %c\n”, initial);
return 0;
}
Output
Key Points
- Variables must be declared before use.
- You can assign values during declaration or separately.
- Use meaningful variable names to improve code readability.