Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Variables

A variable is a named place in memory that holds a value. A program uses variables to remember things: a score, a price, a letter typed by the user. In C every variable has a type, which decides what kind of value it holds.

Declaring a variable

To create a variable, write its type and its name, then a semicolon. This is called a declaration. You can give the variable its first value at the same time, which is called initialisation.

#include <stdio.h>

int main(void) {
    int age = 12;          // a whole number
    float height = 1.45f;  // a number with a decimal point
    char grade = 'A';      // a single character

    printf("Age: %d\n", age);
    printf("Height: %.2f\n", height);
    printf("Grade: %c\n", grade);
    return 0;
}
Output
Age: 12
Height: 1.45
Grade: A

%d, %.2f and %c are the format specifiers for an int, a float with two decimals and a char. The next topic explains them.

Changing a value

A variable's value can change while the program runs: assigning a new value with = replaces the old one.

#include <stdio.h>

int main(void) {
    int score = 10;
    printf("Score: %d\n", score);
    score = 25;               // replace the value
    printf("Score: %d\n", score);
    score = score + 5;        // use the old value to compute the new one
    printf("Score: %d\n", score);
    return 0;
}
Output
Score: 10
Score: 25
Score: 30

Several variables at once

Variables of the same type can be declared on one line, separated by commas: int x = 5, y = 6, z = 50;.

Always give variables a value

A variable declared without a value, such as int total;, contains whatever happened to be in that memory: a "garbage" value. Using it before giving it a value is a common bug, and the compiler warns about it with -Wall. Initialise every variable, even with 0.

Naming rules

  • Names may contain letters, digits and the underscore _, and must not start with a digit.
  • Names are case sensitive: score and Score are different.
  • Keywords such as int, return or while cannot be used as names.
  • Choose names that say what the value means: price is better than p, studentCount or student_count better than sc.

Practice exercises

  1. Create variables for your age, your height and the first letter of your name, and print them.
  2. Create int a = 7, b = 3;, then swap their values using a third variable and print both.
  3. Declare int total; without a value and print it. Read the warning, then fix the program.