Variables in C
In C, a variable is a named memory location used to store data values. The value stored in a variable can be changed during program execution.
Variables act like containers that store different types of data such as
integers, decimal numbers, or characters.
For example, int marks = 85; creates a variable named
marks.
Syntax:
data_type variable_name = value;
Why Use Variables?
- To store data during program execution.
- To perform calculations and operations on data.
- To make programs flexible and easy to manage.
Rules for Naming Variables
- Variable names must begin with a letter or underscore (_).
- They can contain letters, digits, and underscores.
- Spaces and special characters are not allowed.
- C is case-sensitive.
- Variable names should not be keywords.
Understanding these rules in more detail:
While declaring variables in C, we must follow these rules:
-
Variable names must begin with a letter or underscore (_)
Valid example:
_count = 10;
student = 1;
Invalid example:
1marks = 50; // Invalid: starts with digit @price = 20; // Invalid: starts with special character -
Variable names can contain letters, digits, and underscores
Valid example:
total_1 = 95;
roll_no = 12;
Invalid example:
my-name = 20; // Invalid: contains hyphen my marks = 90; // Invalid: contains space -
C is case-sensitive
This means
Totalandtotalare different variables.Example:
int Total = 50; int total = 100; printf("%d\n", Total); printf("%d", total);Output:
50
100
-
Variable names should not be C keywords
Examples of keywords:
int,while,return,forExample:
int int = 10; // Invalid float while = 5; // Invalid -
Variable names should be meaningful
Use
studentMarksinstead ofsmfor better readability.
Example Program: Variable Usage in C
// Program to demonstrate variables in C
#include <stdio.h>
int main() {
int salary = 15000;
printf("Initial Salary = %d\n", salary);
salary = 20000;
printf("Updated Salary = %d", salary);
return 0;
}
Output:
Initial Salary = 15000
Updated Salary = 20000
Explanation:
salaryis a variable used to store salary value.- The value of
salaryis first 15000. - Later, the value is changed to 20000.
- This shows that variable values can change during program execution.
Real-Life Analogy:
Think of a variable as a container with a label on it. We can store a value inside the container and replace it whenever needed. Similarly, variables in C store values that can change during program execution.
Common Mistakes with Variables
- Using variables without initializing them.
- Using confusing variable names.
- Using spaces or special characters in variable names.
- Forgetting that C is case-sensitive.
Summary:
- Variables are used to store data values in memory.
- The value of a variable can change during program execution.
- Variable names must follow naming rules.
- C is case-sensitive.
- Meaningful variable names improve readability.