Constants

Some values never change while a program runs: the VAT rate, the number of days in a week, the maximum number of points in a test. For them, C has constants. A constant is a variable with const in front of it:

const double VAT_RATE = 0.21;

const (from constant) means that the value can't change. A constant gets its value when it's created, and keeps it until the program ends. Constants are written in UPPER_CASE, with underscores between the words, so that you can tell at a glance that a name is a constant.

Why not just write 0.21 into the calculation? There are three good reasons:

  • The name explains the number. price * VAT_RATE says what's going on; with price * 0.21, you have to guess.
  • If the rate changes, you change it in one place, and every calculation that uses it changes with it.
  • The compiler watches over it. If you change a constant by mistake, the program doesn't compile.
#include <stdio.h>

int main(void) {
    const double VAT_RATE = 0.21;
    VAT_RATE = 0.15;
    printf("%.2f\n", VAT_RATE);
    return 0;
}

The compiler reports:

main.c:5:14: error: cannot assign to variable 'VAT_RATE' with const-qualified type 'const double'

It says that you can't assign a new value to VAT_RATE, because its type is const double. Otherwise, you use a constant like any other variable:

const double VAT_RATE = 0.21;
double price = 40.0;
printf("VAT: %.2f EUR\n", price * VAT_RATE);

This prints:

VAT: 8.40 EUR

And how do you print a percent sign? In printf, % starts a format specifier, such as %d. To print the sign itself, write it twice, %%:

printf("VAT is %d%%\n", 21);

This prints:

VAT is 21%

With only one %, as in "VAT is 21%\n", the program doesn't compile. The compiler reports invalid conversion specifier '\x0a': after the %, it expected a letter like d, but it found a new line (\x0a is how it writes \n).

Instructions

A test has a maximum of 50 points. At the start of main, create a constant MAX_POINTS of type int with the value 50.

Change the printf so that it prints the maximum too, taken from the constant:

Points: 42 of 50

On the next line, print the result in percent: the points times 100, divided by MAX_POINTS. Multiply first: 42 / 50 on its own is 0, as you know. Print the percent sign with %%:

Result: 84%

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/11