Update shortcuts
Changing a variable based on its old value is so common that C has shortcuts:
| Shortcut | Same as |
|---|---|
x += 5; | x = x + 5; |
x -= 5; | x = x - 5; |
x *= 2; | x = x * 2; |
x /= 2; | x = x / 2; |
x++; | x = x + 1; |
x--; | x = x - 1; |
#include <stdio.h>
int main() {
int coins = 10;
coins += 5;
printf("%d\n", coins);
coins *= 2;
printf("%d\n", coins);
coins--;
printf("%d\n", coins);
return 0;
}Output
15 30 29
Tip:
++and--are used all the time in loops (Module 5). Use them on a line of their own to keep things simple.
Type casting: changing the type
Sometimes you have two ints but want an exact decimal answer – for example an average. Write the type you want in brackets in front of a value. This is called a cast:
#include <stdio.h>
int main() {
int total = 17;
int count = 4;
printf("Without cast: %d\n", total / count);
printf("With cast: %.2f\n", (double) total / count);
return 0;
}Output
Without cast: 4 With cast: 4.25
(double) total turns 17 into 17.0 for this calculation, so the division keeps the decimals.
A cast also works the other way. (int) cuts off the decimal part:
#include <stdio.h>
int main() {
double price = 19.99;
int euros = (int) price;
printf("%d\n", euros);
return 0;
}Output
19
Remember:
(double)before a value makes division exact.(int)chops off the decimals.