Lesson 4 of 7 · C Foundations · 2 min read · Updated

Variables and types

Boxes that hold values — and why C insists on knowing what kind of value goes in each one.

A variable is a named place in memory that holds a value. In C you must say what kind of value it will hold before you use it. That is called declaring it.

A variable is a named box in memory: it has a type, a value and an address.
c
#include <stdio.h>

int main(void)
{
    int    age = 25;
    float  height = 1.75f;
    char   grade = 'A';

    printf("Age: %d\n", age);
    printf("Height: %.2f\n", height);
    printf("Grade: %c\n", grade);

    return 0;
}
Output
Age: 25
Height: 1.75
Grade: A

The types you will use most

  • int — a whole number, such as 25 or -3. Usually 4 bytes, holding roughly -2 billion to +2 billion.
  • float — a number with a decimal point, such as 1.75. About 7 digits of precision.
  • double — like float but twice the precision. Use this unless you have a reason not to.
  • char — a single character, written in single quotes: 'A'. It is really a small integer underneath.

Format specifiers

The %d and %c inside printf are format specifiers. Each one is a slot, and printf fills it with the matching argument. The specifier must match the type, or the output will be nonsense.

c
%d   int
%f   float or double
%.2f float or double, to 2 decimal places
%c   char
%s   string
%%   a literal percent sign

Warning

Using %d for a float does not round it — it prints garbage. The compiler often will not stop you, so this is one to watch.

Note

A variable you declare but never assign holds whatever was in that memory before — not zero. Always give a variable a value before you read it.

Which format specifier prints a float to two decimal places?

Create a free account to save your progress, or sign in.