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: total and Total are two different variables.
ValidInvalid
total_markstotal marks
_count2name
price1my-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:
Exercises & Assignments
Write a C program to swap the values of two variables using a third variable
Write a C program to print words using spacing and new line characters
Write a C program to get the salary from the user and print it
Write a C program to find the size of int, float, long, double and char
Write a C program to get the marks of 5 subjects and find the total and average
Write a C program to calculate the perimeter of a rectangle
Write a C program to convert minutes into hours and minutes
Interview Questions & Answers
What is the difference between a variable and a constant in C?
What are the data types in C?
What is the difference between = and == in C?
What is the difference between ++i and i++ in C?
What is the use of the sizeof operator in C?
How to swap two numbers in C?