CodeBlanks Logo Icon CodeBlanks

const

Learn to declare immutable variables with the const keyword.

The const keyword

The const keyword tells that a variable's value will not change during the program. After declaration, you cannot assign a new value:

const double PI = 3.14;
PI = 3.15;  // error

Constants are named values that make code readable. Writing PI instead of 3.14 states your intent clearly. The compiler forbids accidental changes.

What is const for?

const serves three main purposes:

  • Safety: prevents accidental changes
  • Readability: TAX is more meaningful than 0.18
  • Documentation: states clearly that the value is fixed

Use const for any value that should not change during the program. This conveys your intent to both the compiler and the reader.

Practice Compute with a constant

Define const double TAX = 0.18;. Set double price = 100.0; and print price * TAX with printf using %lf.

Starter code

main.c
// define const TAX, set price = 100.0, print with printf

Sample solution

main.c
#include <stdio.h>

int main(void) {
    const double TAX = 0.18;
    double price = 100.0;
    printf("%lf", price * TAX);
    return 0;
}

Expected output

18.000000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 After const double PI = 3.14;?

  • You can assign any value to PI
  • PI cannot be reassigned Correct answer
  • PI is undefined
  • PI automatically becomes 0

Explanation: A const value cannot be reassigned.

2 const type

Question
const ____ PI = 3.14;
Answer
const double PI = 3.14;

Explanation: PI is a decimal value, so double is used.

3 Match the keywords

Term Meaning
const Constant
int Integer
double Decimal
char Character

All lessons in Beginner