C Variables
A variable is a name given to a memory location. It stores a value that can change while the program runs. In C you must tell the type of the variable before you use it.
Declare and initialize
#include <stdio.h>
int main(void) {
int age = 25; // whole number
float price = 99.5f; // decimal number
char grade = 'A'; // single character
printf("Age: %d\n", age);
printf("Price: %.1f\n", price);
printf("Grade: %c\n", grade);
return 0;
}
Output:
Output of the above program is
Age: 25
Price: 99.5
Grade: A
Declare first and give value later
#include <stdio.h>
int main(void) {
int a, b; // many variables of same type
a = 10;
b = 20;
a = a + 5; // value can change
printf("%d %d\n", a, b);
return 0;
}
Output:
Output of the above program is
15 20
Rules for naming variables
- Use letters, digits and underscore. Name cannot start with a digit.
- No spaces or special characters like
@or-. - Keywords cannot be used as names.
- Names are case sensitive:
totalandTotalare two different variables.
| Valid | Invalid |
|---|---|
total_marks | total marks |
_count | 2name |
price1 | my-price |
Note:
A variable which is declared but not given a value holds a garbage value. Always give the value when you declare it.
Next: C Data Types.
Congratulations! Chapter Finished. Learn more about the similar topics: