Codiqo

Learn C · lesson 11 of 60 · about 7 minutes

Updating and Casting

Count the report's warnings with +=, update values with ++ and --, and use casts to get decimal results from whole numbers.

What you'll learn

  • Use ++ and --
  • Use compound assignment
  • Cast between int and double

Shortcuts for updating

| Shortcut | Same as |
|---|---|
| x++ | x = x + 1 |
| x-- | x = x - 1 |
| x += 5 | x = x + 5 |
| x -= 2 | x = x - 2 |
| x *= 3 | x = x * 3 |
| x /= 2 | x = x / 2 |

Updating a score

#include <stdio.h>

int main(void) {
    int xp = 10;
    xp += 15;
    xp *= 2;
    xp--;
    printf("%d\n", xp);
    return 0;
}

Output

49

Counting with bools

Because true is 1 and false is 0, you can add bools up. warnings += low_space; adds 1 when space is low and nothing when it isn't, so a counter that starts at 0 ends up as the number of things that went wrong.

Adding up warnings

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    bool low_space = true;
    bool can_backup = true;
    int warnings = 0;
    warnings += low_space;
    warnings += !can_backup;
    printf("Warnings: %d\n", warnings);
    return 0;
}

Output

Warnings: 1

Casting

Integer division drops decimals. To get a decimal answer, turn one side into a double with a cast: (double)total / count.

Casting the other way, (int)3.99, chops off the decimals (it doesn't round).

Getting a real average

#include <stdio.h>

int main(void) {
    int total = 7;
    int count = 2;
    printf("%d\n", total / count);
    printf("%.1f\n", (double)total / count);
    printf("%d\n", (int)3.99);
    return 0;
}

Output

3
3.5
3

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.