Types and variables in C — theory with my IC2 grades, printf, scanf and the & (and the average that came out as 7.00 instead of 7.50)

First IC2 lab. I had my four grades from the previous year written in a notebook and thought: “I’ll work out the average in C, it’s just adding and dividing”. Five lines, it compiled without a single warning, and the program told me this:

#include <stdio.h>

int main(void) {
    int theory = 8, practice = 7, test = 6, project = 9;    /* my four IC2 grades */
    float average = (theory + practice + test + project) / 4; /* looks right... */
    printf("Average: %.2f\n", average);
    return 0;
}

Output:

Average: 7.00

8 + 7 + 6 + 9 = 30, and 30 / 4 = 7.5. The average was 7.50, not 7.00. And the strangest part: average is a float, so it had room for decimals. Where had they gone? It took me a while to understand that the problem wasn’t the variable, but the types of the numbers being divided. That’s the idea you’ll see again and again in this article: in C, the type of each piece of data decides what happens to it.

Today we cover the basic C types and how much memory they take, how to declare variables, why char is really a number, integer division and casts, true and false as 1 and 0, and the two functions you’ll use in every IC2 program: printf and scanf (with its famous &). If your environment isn’t ready yet, start with the guide to gedit and gcc on Fedora. And when you finish, the types and variables in C practice is waiting for you.

In a nutshell: In C every variable has a type that decides which values it holds and how much memory it takes: int for integers, char for characters and float and double for decimals. You declare them before using them, print them with printf and its format (%d, %f, %c) and read them with scanf, passing the address with &.

Before you start. For this topic, what you saw in FP1 is enough: what a variable is in Python, print, input with int() and the usual operators. Plus having gcc working, even if all you’ve compiled is a “hello world”. Nothing else. The topic has three big ideas, in this order: the type decides how much memory a piece of data takes and which values fit in it (types, declarations, char and overflow); the type decides how you operate with it (integer division, casts, and true and false as 1 and 0); and printf and scanf talk to the user by trusting a specifier that has to match the type. If you get lost at any point, go back to the 7.00 average: the whole topic can be told with it.

C is not Python: three differences before you start

If you come from Python, a lot of C will feel familiar (the operators are almost the same), but there are three deep differences that explain nearly every early mistake:

  1. Every variable has a fixed type that you declare. In Python you wrote x = 5 and then x = "hello" with no problem. In C you write int x = 5; and x stays an integer for its whole life. This is called static typing: the type is decided when compiling, not when running.
  2. Every statement ends with a semicolon. In Python a line break was enough; in C, without ;, gcc won’t compile.
  3. The program is compiled before it runs. gcc reads the whole file, checks the types and produces an executable. Many errors show up as warnings that you have to read, because the program can compile and still be wrong.
PythonC
x = 5 (Python works out the type)int x = 5; (you state the type)
print(f"Grade: {grade:.2f}")printf("Grade: %.2f\n", grade);
age = int(input("Age: "))scanf("%d", &age);
True / False1 / 0 (and bool with <stdbool.h>)
7 / 2 gives 3.5 and 7 // 2 gives 37 / 2 gives 3 (between integers)
int with no size limit4-byte int: up to 2147483647

Why so strict? Because C works close to the hardware. When you declare int x, the compiler reserves exactly 4 bytes and knows how to add with them without asking anything while the program runs. Python stores information about the type next to every value, and that costs memory and time. C skips all of that.

The basic C types and how much they take

C has few basic types, and all of them are numbers: integers (char, short, int, long) and decimals (float, double). What changes between them is how many bytes they take, and that decides which values fit. This program asks directly with sizeof, which returns the size in bytes:

#include <stdio.h>
#include <limits.h>   /* CHAR_MIN, INT_MAX, LONG_MAX, UINT_MAX... */
#include <float.h>    /* FLT_DIG and DBL_DIG: reliable decimal digits */

int main(void) {
    /* sizeof gives the size in bytes; %zu is the format of its type (size_t) */
    printf("Type          Bytes  Range\n");
    printf("char          %zu      %d to %d\n", sizeof(char), CHAR_MIN, CHAR_MAX);
    printf("short         %zu      %d to %d\n", sizeof(short), SHRT_MIN, SHRT_MAX);
    printf("int           %zu      %d to %d\n", sizeof(int), INT_MIN, INT_MAX);
    printf("unsigned int  %zu      0 to %u\n", sizeof(unsigned int), UINT_MAX);
    printf("long          %zu      %ld to %ld\n", sizeof(long), LONG_MIN, LONG_MAX);
    printf("float         %zu      about %d reliable digits\n", sizeof(float), FLT_DIG);
    printf("double        %zu      about %d reliable digits\n", sizeof(double), DBL_DIG);
    return 0;
}

I compiled it with gcc -Wall -std=c11 on a 64-bit Linux like Fedora, and this is the output:

Type          Bytes  Range
char          1      -128 to 127
short         2      -32768 to 32767
int           4      -2147483648 to 2147483647
unsigned int  4      0 to 4294967295
long          8      -9223372036854775808 to 9223372036854775807
float         4      about 6 reliable digits
double        8      about 15 reliable digits

Look at the drawing: each box is one byte. With 1 byte (char) there are 2⁸ = 256 combinations, from -128 to 127. With 4 bytes (int), 2³² combinations: from -2147483648 to 2147483647. That’s why an int can’t hold 3 billion, and Python can: Python integers grow as much as they need.

Size of the C typesByte bars: char 1, short 2, int 4, float 4, double 8 and long 8 bytes, with their range or reliable digits.How many bytes each type takes (sizeof on 64-bit Fedora)charB1 byte-128 to 127shortBB2 bytes-32768 to 32767intBBBB4 bytes±2147483647 (about 2.1 billion)floatBBBB4 bytesabout 6 reliable digitsdoubleBBBBBBBB8 bytesabout 15 reliable digitslongBBBBBBBB8 bytes±9.2 quintillion (on Fedora)Violet: integers (exact values) · coral: decimals (approximate)
Each box is one byte: more bytes means more range (integers) or more reliable digits (decimals).

Where those ranges come from

Before memorising numbers, let’s work them out ourselves. A byte is 8 bits, and each bit is a box that can only hold 0 or 1. The question that settles everything is: how many different numbers can you write with those boxes?

With 1 bit there are 2 possibilities: 0 and 1. Every bit you add doubles the combinations, because each combination you already had can go with a 0 in front or with a 1 in front:

BitsCombinationsWhy
120 or 1
24the previous 2 with a 0 in front and with a 1 in front: 00, 01, 10, 11
38double again: 2 × 2 × 2
8 (a char)2562 multiplied by itself 8 times: 2⁸
16 (a short)655362¹⁶
32 (an int)42949672962³², about 4.3 billion

Those combinations have to be shared out among numbers. If the type is unsigned (positives only), all of them are used starting from 0: with 8 bits, from 0 to 255. The maximum is 255 and not 256 because one of the 256 combinations is spent on the 0.

If the type is signed, half of the combinations go to the negatives and the other half to 0 and the positives. With 8 bits you get 128 negatives (from -128 to -1) and 128 for the rest (0 and 1 to 127). That’s why the range isn’t symmetrical: there’s one more negative than positives, because 0 takes up a place on the positive side.

TypeBitsCombinationsHalfSignedUnsigned
char8256128-128 to 1270 to 255
short166553632768-32768 to 327670 to 65535
int3242949672962147483648-2147483648 to 21474836470 to 4294967295

Compare the last row with the output of the sizeof program: they’re exactly the values of INT_MIN, INT_MAX and UINT_MAX. You don’t need to memorise them; it’s enough to know how many bytes the type takes and do this sum.

Check you’ve got it: what’s the largest number that fits in an unsigned short (2 bytes)?

It’s 65535. That’s 16 bits, so there are 2¹⁶ = 65536 combinations. Unsigned uses all of them starting from 0, and the 0 spends one: the maximum is 65536 − 1 = 65535. Signed, the maximum would be half minus one, 32767, which is exactly the SHRT_MAX in the output.

Decimals work differently: they don’t store exact values, but approximations. A float gives about 6 reliable digits and a double about 15. For IC2 grades, prices and averages either one works, but if in doubt, double is C’s “default” decimal: literals like 7.5 are double unless you add an f (7.5f).

Modifiers. Integers can take unsigned (positive only, twice the maximum), short (fewer bytes) or long (more bytes): unsigned int counter = 0;, long long big = 9000000000;. In IC2 you’ll use int for almost everything and unsigned when the value can’t be negative, like a size.

I want to store…TypeExample
A normal whole number (age, credits, ID number)intint credits = 60;
A single letter or symbolcharchar group = 'B';
A number with decimals (grade, price)float or doubledouble grade = 7.75;
An integer that is never negativeunsigned intunsigned int times = 0;
An integer bigger than 2147483647long longlong long population = 8100000000LL;

The size of long depends on the system. On 64-bit Fedora it takes 8 bytes, as you can see in the output, but on Windows it takes 4. char is always 1 byte and int is 4 on every computer you’ll use during your degree. If you need 8 bytes for sure, use long long.

Declaring variables: initial value, const and #define

Before the syntax, think about what a variable is in C, because it isn’t the same as in Python. In Python, x = 5 creates a 5 somewhere in memory and sticks the label x on it; if you then write x = "hello", the label comes off and gets stuck on another object. In C the variable is the box itself: a piece of memory with a name, a fixed size and some contents. When you declare it you decide three things, and each one has its consequence:

In int age = 19;What it isWhy it matters
intthe typesays how many bytes are reserved (4) and how those bytes are read: as an integer, not as a letter or a decimal
agethe nameit’s how you refer to that box in the rest of the program; it can’t start with a digit or contain spaces
= 19the initial valuethe first thing written inside; if you leave it out, the box keeps whatever was in that memory before

The type can’t be changed afterwards: age will be a 4-byte int until the program ends. What does change, as many times as you like, is what’s inside. With that picture in your head, the syntax is easy.

Declaring a variable means telling C its type and its name: type name; or, better, type name = value;. You can declare several of the same type on one line (int a = 1, b = 2;), and C is case-sensitive: grade and Grade are two different variables. Look at this program, which has a deliberate trap in the last variable:

#include <stdio.h>
#define IC2_CREDITS 6              /* #define: the preprocessor swaps the name for 6 before compiling */

int main(void) {
    const float PASS_MARK = 5.0f;   /* const: a typed variable that cannot change */
    int age = 19;                   /* declare and initialise on the same line */
    float grade = 7.75f;            /* the final f: float literal (without it, double) */
    char group = 'B';               /* single quotes: ONE character */
    int sittings;                   /* declared without a value: whatever was in that memory */

    printf("Age: %d, grade: %.2f, group: %c\n", age, grade, group);
    printf("IC2 credits: %d, pass mark %.1f\n", IC2_CREDITS, PASS_MARK);
    printf("Exam sittings (uninitialised): %d\n", sittings);
    return 0;
}

When compiling, gcc already warns about the trap:

declare.c: In function 'main':
declare.c:13: warning: 'sittings' is used uninitialized [-Wuninitialized]
declare.c:9: note: 'sittings' was declared here

And running it prints this:

Age: 19, grade: 7.75, group: B
IC2 credits: 6, pass mark 5.0
Exam sittings (uninitialised): 32766

sittings has no value assigned, so printf shows whatever was in those 4 bytes of memory: in my run, 32766. On your computer you may get another number, or 0, or it may change from one run to the next. That’s garbage: C doesn’t clean memory for you.

Using a variable without giving it a value. In Python, using a variable that doesn’t exist raises a NameError and the program stops. In C it compiles (with a warning many people don’t read) and carries on with any old value. Rule: always initialise, even if it’s to 0 (int sittings = 0;).

Two ways to make constants. The program has both:

  • #define IC2_CREDITS 6 is not a variable: the preprocessor swaps the text IC2_CREDITS for 6 before compiling. It has no type, takes no memory, and has no ; or =.
  • const float PASS_MARK = 5.0f; is a variable, with its type, but read-only. If you try PASS_MARK = 4.0f;, gcc gives a compile error: assignment of read-only variable.
#defineconst
What it isText substitution before compilingA variable that cannot change
Has a typeNoYes (the compiler checks it)
Syntax#define PI 3.14159f (no = or ;)const float PI = 3.14159f;
In IC2 you’ll see itA lot (array sizes, constants)In functions and parameters

Write constants in CAPITALS (PI, IC2_CREDITS). It isn’t required, but it shows at a glance which values never change, just like the Python convention.

char: a number dressed up as a letter

This is what surprises people most coming from Python: C has no “letter” type. A char is a 1-byte integer, and the letter you see is just one way of showing that number according to the ASCII table (‘A’ is 65, ‘a’ is 97, ‘0’ is 48). With %c printf shows the letter; with %d, the number. And since it’s a number, you can add to it:

#include <stdio.h>

int main(void) {
    char initial = 'S';
    char digit = '7';

    printf("%c is code %d\n", initial, initial);          /* the same byte with two formats */
    printf("The next letter: %c\n", initial + 1);         /* 83 + 1 = 84, which is 'T' */
    printf("In lowercase: %c\n", initial + 32);           /* 'a' - 'A' = 97 - 65 = 32 */
    printf("'7' is %d, but '7' - '0' = %d\n", digit, digit - '0');
    printf("'A' + 'B' = %d\n", 'A' + 'B');                /* 65 + 66: char adds up too */
    return 0;
}

Output:

S is code 83
The next letter: T
In lowercase: s
'7' is 55, but '7' - '0' = 7
'A' + 'B' = 131

Line by line:

  • 'S' is stored as 83. With %c you get S; with %d, 83. Same byte.
  • initial + 1 is 83 + 1 = 84, and 84 in ASCII is T. That’s how the Caesar-style ciphers in the first C exercises work.
  • initial + 32 is 83 + 32 = 115, which is s. In ASCII lowercase letters sit exactly 32 places after the capitals (97 − 65 = 32).
  • '7' isn’t 7, but 55 (the character code). To go from character to digit you subtract '0': 55 − 48 = 7. You’ll use it when you read numbers character by character.
  • 'A' + 'B' gives 131 (65 + 66): it doesn’t join them, it adds them.

If you find it hard to believe that a letter is a number, think about what’s really in memory. In the byte of initial there’s no S drawn anywhere: there are eight bits, 01010011. Read as a number they’re 64 + 16 + 2 + 1 = 83. The one who decides what to do with that 83 is printf: with %d it writes it as it is, and with %c it looks up which character has code 83 in the ASCII table and draws an S. The letter only exists on the screen.

To turn a lowercase letter into a capital, subtract 32: 'b' - 32 is 98 − 32 = 66, which is 'B'. It works because in ASCII every lowercase letter sits exactly 32 places after its capital, and it’s the same sum as the initial + 32 in the program, but the other way round.

Mixing up quotes. 'A' (single) is a char, the number 65. "A" (double) is a string: an array of characters that ends with a null character. char c = "A"; tries to put the address of a string into a char, and since gcc 14 it’s a compile error: initialization of 'char' from 'char *' makes integer from pointer without a cast.

Overflow and literals: what doesn’t fit wraps around

What happens if a value doesn’t fit in its type? For unsigned types C is clear: it wraps around, like the odometer of an old car. And while we’re at it, watch how you write numbers, because a leading 0 changes the base:

#include <stdio.h>
#include <limits.h>

int main(void) {
    unsigned char byte = 255;          /* the unsigned 8-bit maximum */
    byte = byte + 1;                   /* 256 does not fit: wraps around to 0 */
    printf("255 + 1 in unsigned char = %d\n", byte);

    unsigned int counter = 0;
    counter = counter - 1;             /* below 0: wraps around to the maximum */
    printf("0 - 1 in unsigned int    = %u\n", counter);

    int big = INT_MAX;
    long long wider = (long long)big + 1;   /* with a wider type it fits */
    printf("INT_MAX                  = %d\n", big);
    printf("INT_MAX + 1 in long long = %lld\n", wider);

    int octal = 010;                   /* starts with 0: it is octal! */
    int hexa = 0x1F;                   /* starts with 0x: hexadecimal */
    printf("010 = %d and 0x1F = %d\n", octal, hexa);
    return 0;
}

Output:

255 + 1 in unsigned char = 0
0 - 1 in unsigned int    = 4294967295
INT_MAX                  = 2147483647
INT_MAX + 1 in long long = 2147483648
010 = 8 and 0x1F = 31
  • 255 is the maximum of an unsigned char (8 bits set to 1). Adding 1 would need 9 bits, the extra one is lost and you get 0.
  • The other way round, 0 − 1 in an unsigned int wraps to the maximum: 4294967295 (2³² − 1). That’s why an unsigned counter that goes below 0 gives huge numbers.
  • INT_MAX + 1 in an int isn’t allowed: for signed types, overflow is undefined behaviour and the compiler may do anything. The fix is to move to a wider type before adding: (long long)big + 1 gives 2147483648.
  • 010 isn’t ten: a leading 0 means octal (base 8), and 010 in octal is 8. 0x1F is hexadecimal: 1 × 16 + 15 = 31.

Wrapping around, bit by bit

“Wraps around” sounds like magic, but it’s just what we saw with the ranges: if the result needs more bits than the type has, the extra one has no box and gets lost. This is what 255 + 1 looks like in an unsigned char:

StepBitsValueWhy
byte = 25511111111255all 8 bits set to 1: the unsigned maximum
+ 11 00000000256like adding 999 + 1 in decimal: every 1 carries one and a new digit appears in front
stored000000000the byte only has 8 boxes; the ninth bit doesn’t fit and is thrown away

It’s the odometer: with three digits, after 999 comes 000. And backwards too: if an odometer showing 000 goes back one, it shows 999. That’s 0 - 1 in an unsigned int: you’re left with all 32 bits set to 1, which is 4294967295, the maximum.

The quick sum is this: you add or subtract the type’s number of combinations (256 for a byte, 4294967296 for an unsigned int) to the result until it fits. For example, an unsigned char that holds 250 and gets 10 added would have to store 260, which doesn’t fit; 260 − 256 = 4, and that’s what it stores (I checked it with gcc). With signed types there’s no sum that works: overflow is undefined, and that’s why the only safe fix is to use a wider type before it happens.

Padding numbers with leading zeros (int day = 08;). Besides being octal, 8 isn’t a valid octal digit, so gcc gives an error. To show zeros in the output you use the printf format (%02d), not the literal.

Operators and integer division

The arithmetic operators are Python’s: +, -, *, / and %. There’s no ** (powers are multiplied by hand or done with pow from <math.h>) and no //. And here is the culprit behind my 7.00:

#include <stdio.h>

int main(void) {
    int total = 30, n = 4;       /* 8 + 7 + 6 + 9 = 30 points over 4 grades */

    printf("30 / 4        = %d\n", total / n);             /* int / int gives int: 7 */
    printf("30 %% 4        = %d\n", total % n);            /* the remainder: 30 = 4 * 7 + 2 */
    printf("30 / 4.0      = %.2f\n", total / 4.0);         /* 4.0 is a double: real division */
    printf("(float)30 / 4 = %.2f\n", (float)total / n);    /* cast BEFORE dividing: 7.50 */
    printf("(float)(30/4) = %.2f\n", (float)(total / n));  /* cast AFTER: it was already 7 */
    printf("-7 / 2        = %d\n", -7 / 2);                /* truncates towards zero: -3, not -4 */
    printf("-7 %% 2        = %d\n", -7 % 2);               /* the remainder takes the sign of the dividend */
    printf("(int)7.99     = %d\n", (int)7.99);             /* to int: chops the decimals, no rounding */
    return 0;
}

Output:

30 / 4        = 7
30 % 4        = 2
30 / 4.0      = 7.50
(float)30 / 4 = 7.50
(float)(30/4) = 7.00
-7 / 2        = -3
-7 % 2        = -1
(int)7.99     = 7

C’s rule is: if both operands are integers, the division is an integer division and the decimals are thrown away (not rounded: chopped). 30 / 4 = 7 remainder 2 (4 × 7 + 2 = 30). It’s enough for one of the two to be a decimal for the division to be real: 30 / 4.0 or (float)total / n.

The drawing shows why my program at the start failed even though average was a float: first the division is worked out, with integers, and then the result is stored. By the time the 7 reaches the float, the .5 no longer exists.

Integer division versus real divisionTop: 30 / 4 between integers gives 7, stored in a float as 7.00. Bottom: the cast turns 30 into 30.0 before dividing and gives 7.50.Where do the decimals get lost? Order mattersfloat media = 30 / 4; (the hook)30 / 4int / int7int: .5 dropped7.00stored in a float  7.00float media = (float)30 / 4;(float)30cast first30.0f / 4float / int7.50real division  7.50Rule: just ONE of the two operands has to be float or double before dividing.
Storing the result in a float comes too late: the division already happened with integers.

That’s why these two lines of the output are different:

  • (float)30 / 4 turns 30 into 30.0 before dividing: 30.0 / 4 = 7.50.
  • (float)(30 / 4) divides first (7) and converts afterwards: 7.00. The cast came too late.

That (float) in front of a value is a cast, an explicit type conversion. It also works downwards: (int)7.99 gives 7, because converting to integer chops the decimals. And with negatives, division truncates towards zero: −7 / 2 gives −3 (not −4 like Python’s //), and the remainder takes the sign of the dividend: −7 % 2 = −1.

I want…CodeResult
How many times b fits in aa / b (two int)30 / 4 → 7
What’s left overa % b30 % 4 → 2
The division with decimals(float)a / b or a / 4.07.50
To drop the decimals(int)x(int)7.99 → 7
To round to the nearest integer (positives)(int)(x + 0.5)(int)(7.75 + 0.5) → 8

My 7.00 average, step by step

With all this you can now read the program from the beginning the way C reads it. The key is that C calculates from the inside out and, in each operation, looks only at the two operands in front of it, not at the variable where you’re going to store the result. This is the line float average = (theory + practice + test + project) / 4;:

StepWhat C calculatesOperand typesResultWhy
1theory + practice + test + projectint and int30 (int)adding integers gives an integer; nothing is lost here
230 / 4int and int7 (int)two integers: integer division, and the remainder (2) is thrown away
3average = 7an int going into a float7.0the conversion to float arrives now, when the .5 no longer exists
4printf("%.2f", average)float7.00printf shows what’s stored, with two decimals

With the fix, (theory + practice + test + project) / 4.0f, only step 2 changes: now it’s an int divided by a float, so C first turns the 30 into 30.0 and does a real division, which gives 7.5. In step 3 there’s nothing left to convert, and printf shows 7.50.

What happens in that step 2 has a name: when you mix an integer and a decimal in an operation, C converts the integer to the decimal type before operating. It’s an implicit conversion, because you don’t write it (the cast is the explicit one). And it always goes towards the type that can hold more: it never throws away the other operand’s decimals to make it fit in the int.

Check you’ve got it: what does double r = 7 / 2 * 2.0; store?

6.0, not 7.0. C goes from left to right: first 7 / 2, which are two integers and gives 3; then 3 * 2.0, which mixes int and double, so the 3 becomes 3.0 and you get 6.0. If you write 7 * 2.0 / 2, the first step is already 14.0 (a double) and the result is 7.0. Same numbers, different order, different result. I checked it with gcc: 6.00 and 7.00.

Whenever you write a division, ask yourself what type each side has. If both are int, the result is int, wherever you store it. A .0 or a (float) on one operand fixes it.

% only works with integers. 7.5 % 2 doesn’t compile: invalid operands to binary %. For the remainder of two decimals there’s fmod in <math.h>.

True and false in C: 1, 0 and bool

In C a comparison doesn’t return True or False: it returns an int, 1 if it holds and 0 if it doesn’t. And the other way round, when C needs a condition, any value other than 0 counts as true. Since C99 there’s bool in <stdbool.h>, but inside it’s still 0 or 1. In the same program I also show increments and compound assignment:

#include <stdio.h>
#include <stdbool.h>      /* bool, true and false (since C99) */

int main(void) {
    float grade = 7.75f;
    int passed = grade >= 5.0f;                  /* a comparison is 1 or 0 */
    int merit = grade >= 7.0f && grade < 9.0f;   /* && also gives 1 or 0 */
    bool repeater = false;                       /* bool exists, but inside it is 0 or 1 */
    printf("passed = %d, merit = %d, !passed = %d, repeater = %d\n",
           passed, merit, !passed, repeater);

    int x = 5;
    int a = x++;     /* a gets 5 and THEN x becomes 6 */
    int b = ++x;     /* x becomes 7 and THEN b gets 7 */
    printf("a = %d, b = %d, x = %d\n", a, b, x);

    int credits = 6;
    credits += 6;    /* credits = credits + 6 -> 12 */
    credits *= 2;    /* 24 */
    credits %= 10;   /* the remainder of 24 divided by 10 -> 4 */
    printf("credits = %d\n", credits);
    return 0;
}

Output:

passed = 1, merit = 1, !passed = 0, repeater = 0
a = 5, b = 7, x = 7
credits = 4
  • grade >= 5.0f is 1, and it can be stored in an int and added up. We’ll use it in the practice to count passes without a single if.
  • && (and), || (or) and ! (not) are Python’s and, or and not, and they also give 1 or 0. !passed is 0 because passed is 1.
  • x++ and ++x both add 1 to x, but they don’t return the same thing. a = x++ gives a the old value (5) and then raises x to 6. b = ++x raises x to 7 first and then gives it to b. That’s why you get 5, 7 and 7.
  • +=, *= and %= are Python’s: 6 + 6 = 12, 12 × 2 = 24 and 24 % 10 = 4.

x++ and ++x, line by line

The difference between x++ and ++x is only one of order: both raise x by 1, but one hands over the value before raising it and the other after. This is how the program goes, with x starting at 5:

Linex beforeWhat the variable getsx afterWhy
int x = 5;doesn’t existx = 55a normal declaration
int a = x++;5a = 56x++ hands over the old value and then adds
int b = ++x;6b = 77++x adds first and hands over the new value

One way to remember it is to read from left to right: in x++ the x comes first (it’s used) and then the ++ (it’s added); in ++x, the other way round. If the ++ is alone on its line (x++;), it doesn’t matter which one you write, because nobody picks up the value.

Check you’ve got it: with int x = 3; , what are y and x after int y = x++ + 10; ?

y is 13 and x is 4. x++ hands over the old value, 3, so y = 3 + 10 = 13; then x goes up to 4. With ++x + 10 you’d get y = 14, because x would go up to 4 before being used.

Writing = where you meant ==. if (grade = 10) doesn’t compare: it assigns 10 to grade and, since 10 isn’t 0, the condition always holds. gcc with -Wall warns you (suggest parentheses around assignment used as truth value). We’ll see it in depth in conditionals in C.

With -std=c11, as in IC2, bool needs #include <stdbool.h>. In the C23 standard (the default in gcc 15, the one in Fedora 42 onwards) bool, true and false are already keywords.

printf: specifiers, widths and decimals

printf (from <stdio.h>) prints to the screen. Its first argument is a format string with normal text and slots that start with %; the other arguments fill those slots, in order. The drawing shows it with the line we’ll use in the scanf section: the first slot with the first argument, the second with the second… and the type of each slot has to match the type of the value.

How printf and scanf workTop: printf’s %d, %.2f and %c specifiers pair up in order with age, grade and group. Bottom: scanf receives &age, the variable’s address, and writes 19 into its 4 bytes.printf fills slots; scanf needs addressesprintf(“Age %d, grade %.2f, group %c\n”, age, grade, group);Output:Age 19, grade 7.75, group BThe 1st slot takes the 1st argument, the 2nd the 2nd… and the type has to match.scanf(“%d”, &age);&age = “the address of age”age (int, 4 bytes) = 190x7ffc4237f29c13000000Without &, scanf gets the (garbage) value instead of the address and writes where it shouldn’t.
printf needs values; scanf needs to know where to store: that is why it takes &.

This program goes through the specifiers and modifiers you’ll need (the brackets are there so you can see the spaces):

#include <stdio.h>

int main(void) {
    int credits = 6;
    float grade = 7.75f;
    double average = 7.753;

    printf("[%d] [%5d] [%-5d] [%05d]\n", credits, credits, credits, credits);
    printf("[%f] [%.2f] [%8.2f] [%.0f]\n", grade, grade, grade, grade);
    printf("[%e] [%.3lf]\n", average, average);       /* in printf, %f and %lf are the same */
    printf("[%x] [%X] [%o] [%%]\n", 255, 255, 255);
    printf("[%c] [%s]\n", 'B', "IC2");
    printf("Tab:\t|Quotes: \"ok\"|Backslash: \\|\n");
    return 0;
}

Output:

[6] [    6] [6    ] [00006]
[7.750000] [7.75] [    7.75] [8]
[7.753000e+00] [7.753]
[ff] [FF] [377] [%]
[B] [IC2]
Tab:	|Quotes: "ok"|Backslash: \|
  • %5d reserves 5 spaces and aligns right; %-5d, left; %05d pads with zeros. They’re for tables that line up.
  • %f prints 6 decimals; %.2f, 2; %8.2f, 2 decimals in 8 spaces; %.0f rounds to an integer (7.75 → 8). Careful: here it does round, because it only changes how the value is written, not the value itself.
  • %e writes in scientific notation (7.753 = 7.753000 × 10⁰).
  • %x, %X and %o write the same number in hexadecimal and octal: 255 is ff and 377.
  • %% prints a %, because a single % would just start a specifier.
  • \t is a tab, \" a double quote and \\ a backslash: they’re escape sequences, just like in Python.
SpecifierType of the valueExamplePrints
%dint (and char as a number)printf("%d", 60)60
%uunsigned intprintf("%u", 4294967295u)4294967295
%ld / %lldlong / long longprintf("%lld", 2147483648LL)2147483648
%f, %.2ffloat or doubleprintf("%.2f", 7.753)7.75
%efloat or doubleprintf("%e", 7.753)7.753000e+00
%ccharprintf("%c", 66)B
%sstringprintf("%s", "IC2")IC2
%x / %X / %oint in base 16 / 16 / 8printf("%X", 255)FF
%zusize_t (what sizeof returns)printf("%zu", sizeof(int))4
%pmemory addressprintf("%p", (void *)&x)0x7ffc…

What happens if the specifier doesn’t match

printf doesn’t know the types of its arguments: it trusts the format string. If you promise it a float and give it an int, it reads the bytes as something they aren’t:

#include <stdio.h>

int main(void) {
    int credits = 6;
    float grade = 7.75f;

    printf("Credits with %%f: %f\n", credits);   /* int with %f: undefined behaviour */
    printf("Grade with %%d: %d\n", grade);       /* float with %d: another meaningless number */
    return 0;
}

gcc spots it when compiling:

bad_format.c: In function 'main':
bad_format.c:7: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
bad_format.c:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]

But it compiles anyway, and this is the output:

Credits with %f: 0.000000
Grade with %d: -680103264

Neither 6.000000 nor 7: a 0.000000 and a meaningless negative number. Notice a detail in the second warning: it says the argument is a double, not a float. When you pass a float to printf, C always converts it to double; that’s why in printf %f works for both (and so does %lf). In scanf, as you’ll see now, it doesn’t.

Why exactly 0.000000 and that negative number? On a 64-bit Linux, integers and decimals reach printf along different paths: some processor registers for integers and others for decimals. With %f, printf goes looking for a double on the decimals path, but the 6 travelled along the integers path, so it reads whatever was there (in my run, zeros). With %d it’s the other way round: the 7.75 travelled along the decimals path and printf reads an integer from a place nobody has filled. That’s why the number changes from one computer to another: it isn’t a badly done conversion, it’s reading from the wrong place.

Ignoring -Wformat warnings. A wrong specifier doesn’t break compilation, but the output is garbage and changes from one computer to another. Always compile with -Wall and treat every warning as if it were an error.

scanf and the &: reading data from the keyboard

scanf is printf’s partner: it reads what the user types and stores it in variables. It uses the same specifiers, but with two differences you need to burn into memory: every variable gets a & in front and a double is read with %lf. I ran it typing 19, 7.75 and B:

#include <stdio.h>

int main(void) {
    int age;
    double grade;      /* double: read with %lf in scanf */
    char group;

    printf("Age: ");
    scanf("%d", &age);          /* &age = the address of age: scanf writes there */
    printf("Average grade: ");
    scanf("%lf", &grade);       /* %lf for double (in printf %f is enough) */
    printf("Group: ");
    scanf(" %c", &group);       /* the space skips the leftover Enter */

    printf("Age %d, grade %.2f, group %c\n", age, grade, group);
    printf("age lives at %p and takes %zu bytes\n", (void *)&age, sizeof age);
    return 0;
}

Output (what I typed appears after each question, as in your terminal):

Age: 19
Average grade: 7.75
Group: B
Age 19, grade 7.75, group B
age lives at 0x7ffc4237f29c and takes 4 bytes

Why the &? Because C functions receive copies of values. If you wrote scanf("%d", age), scanf would get a copy of the value of age (garbage, because it has no value yet) and would have no way to change the original variable. &age means “the address of age“: the place in memory where it lives. With that address, scanf can write the 19 right there. Look again at the bottom of the printf drawing: the 19 is stored in the 4 bytes of age as 13 00 00 00 (0x13 = 19, smallest byte first).

The last line of the output makes it visible: %p prints the address of age and sizeof age confirms its 4 bytes. The address changes on every run (Linux places memory in different spots for security), so on your computer you’ll see another one.

ValueIn printfIn scanf
intprintf("%d", age)scanf("%d", &age)
floatprintf("%f", grade)scanf("%f", &grade)
doubleprintf("%f", grade) (or %lf)scanf("%lf", &grade)
charprintf("%c", group)scanf(" %c", &group)
stringprintf("%s", name)scanf("%s", name) (no &: an array is already an address)

Forgetting the &. gcc warns (expects argument of type 'int *', but argument 2 has type 'int') but compiles, and when you run it the usual result is a Segmentation fault. You’ll see it with real output in the exercises.

What scanf does inside, step by step

With the address now understood, look at everything that happens in a single line, scanf("%d", &age), when you type 19 and press Enter. What you type doesn’t go straight into the variable: it stays in a waiting area (the program’s input) and scanf takes from there.

StepWhat scanf doesWhy
1Receives "%d" and the address of agethe %d tells it what to read; the address, where to leave it
2Waits for you to press Enterthe terminal doesn’t hand anything to the program until you finish the line
3Skips the spaces and newlines at the start%d does it on its own (%c doesn’t, as you’re about to see)
4Takes the 1 and the 9they’re digits, so they’re part of the number
5Stops at the \n and leaves it where it wasa newline isn’t a digit: that’s where the number ends
6Converts the text “19” into the integer 19 and writes it into the 4 bytes of agethat’s what it needed the address for
7Returns 1it’s the number of values it managed to store

Look at step 5: the \n stays waiting for the next scanf. That detail is exactly the problem in the next section.

Check you’ve got it: if you type hello in scanf("%d", &age), what is age?

Whatever it was before, because scanf doesn’t touch the variable. In step 4 it finds an h, which isn’t a digit, so there’s no number to convert: it writes nothing and returns 0. I tried it with age set to 42 before reading and afterwards it was still 42 (if age had no value, it still holds garbage). And watch out: “hello” stays in the input, so the next scanf("%d", …) fails again on the same thing and also returns 0.

The space before %c

When you type 19 and press Enter, the program receives three characters: 1, 9 and a newline \n. %d takes the 19, but the \n stays waiting. %d and %lf skip spaces and newlines on their own; %c doesn’t, because a newline is also a character. Look at what happens without the space:

#include <stdio.h>

int main(void) {
    int age;
    char group;

    printf("Age: ");
    scanf("%d", &age);
    printf("Group: ");
    scanf("%c", &group);        /* no space: it takes the Enter from the line before */
    printf("Group read: [%c] (code %d)\n", group, group);
    return 0;
}

I typed 19 and Enter; I didn’t get the chance to type the B:

Age: 19
Group: Group read: [
] (code 10)

scanf didn’t wait: it found the leftover \n and stored it in group (code 10, the newline; that’s why the bracket closes on the next line). The fix is a space before %c: scanf(" %c", &group). A space in a scanf format means “skip all the spaces and newlines you find”.

Put the space in every %c you read after another value. It does no harm when it isn’t needed, and saves you this bug when it is.

Is there a scanf in Python?

No, and it’s a very common search when moving from one language to the other. In Python everything comes in as text with input() and you convert it yourself: age = int(input("Age: ")). In C, scanf reads and converts at the same time, guided by the specifier. That’s why in C the specifier has to match the type: there’s no int() to warn you if the text isn’t a number.

PythonC
age = int(input("Age: "))printf("Age: "); scanf("%d", &age);
grade = float(input("Grade: "))scanf("%lf", &grade); (with double grade;)
a, b = map(int, input().split())scanf("%d %d", &a, &b);
If the text isn’t a number: ValueErrorIf it isn’t a number: scanf stores nothing and returns 0

Common mistakes with types and variables

Dividing two integers and expecting decimals. (8 + 7 + 6 + 9) / 4 gives 7 even if you store it in a float. One operand has to be a decimal: / 4.0 or a cast.

%f in scanf for a double. scanf writes 4 bytes into an 8-byte variable and the value comes out absurd. In printf it doesn’t matter; in scanf, double is %lf.

Using an uninitialised variable. It compiles, prints any old number and changes between runs. Always initialise.

Forgetting the ; at the end of a line. gcc usually complains about the next line (expected ‘;’ before…): when an error makes no sense, look at the line above.

Using int where the value can go past 2147483647, or an unsigned that goes below 0. Both wrap around without warning.

Watch it step by step in Python Tutor

Python Tutor (pythontutor.com) isn’t just for Python: it runs C code line by line and draws every variable with its value. Go there, choose C (gcc) in the language menu and paste this program, which combines the bug from the hook and the char trick:

#include <stdio.h>

int main(void) {
    int theory = 8, practice = 7, test = 6, project = 9;
    int total = theory + practice + test + project;
    float wrong = total / 4;     /* integer division: 7, then 7.0 */
    float right = total / 4.0f;  /* real division: 7.5 */
    char initial = 'S';
    char next = initial + 1;     /* 83 + 1 = 84 */
    printf("%.2f %.2f %c %d\n", wrong, right, next, next);
    return 0;
}

Its output:

7.00 7.50 T 84

Press Next and watch for this:

  1. When the total line runs, a 30 appears in the box for total. So far, all integers.
  2. On the wrong line, the box shows 7: Python Tutor shows that total / 4 was already 7 before it reached the float. It’s the red arrow in the division drawing.
  3. On the right line, the same calculation with 4.0f leaves 7.5. A single .0f changes the result.
  4. In next, the stored value is 84: the char is a number, and printf decides at the end whether to show it as T (%c) or as 84 (%d).

Summary

ConceptWhat you need to remember
Typeschar 1 byte, short 2, int 4, float 4, double 8 (and long 8 on Fedora)
Declaringtype name = value; and always with an initial value
Constants#define PI 3.14159f (text) or const float PI = 3.14159f; (variable)
charA 1-byte number: 'A' is 65 and 'A' + 1 is 'B'
Divisionint / int gives int; with a (float) or a .0 it’s real
Overflowunsigned wraps around; signed is undefined: use a wider type
True/falseComparisons give 1 or 0; anything non-zero is true
printf%d, %f, %.2f, %c, %s, %x, %zu; width with %5d
scanf& in front of each variable, %lf for double and " %c" for char

Three ideas to take away:

  1. In C the type rules: it decides how much a value takes, which values fit and how division works.
  2. printf and scanf trust the specifier: if it doesn’t match the type, the result is garbage even if it compiles.
  3. scanf needs the variable’s address (&) because it has to write into it.

With this you can already write complete programs that read data, calculate and show results. That’s exactly what we do in the types and variables in C practice: a calculator, the IC2 final grade and a student profile with the Spanish ID (DNI) letter. And after the three articles, the next topic: conditionals in C, where that 1 and that 0 start deciding what the program does.

Next step: practiceTypes and variables in C — practice with a calculator, the IC2 final grade and a profile with the DNI letter (and the division by zero that kills the program)

Did this article help you? Here is how you can support SergioLearns →