🎓 A1Learner
🔍
0 of 50 lessons completed

C Constants

Type conversion changed a value from one type to another. A constant is a value that stays fixed as the program runs, and the word const marks a variable as one.

Const int holds a number

LIMIT holds 100, and the value stays fixed. The print line shows 100.

#include <stdio.h>

int main() {
  const int LIMIT = 100;
  printf("%d\n", LIMIT);
  return 0;
}

Capital names mark constants

DAYS_IN_WEEK holds 7 and PI holds 3.14159. Both names use capitals, and the print shows both values.

#include <stdio.h>

int main() {
  const int DAYS_IN_WEEK = 7;
  const double PI = 3.14159;
  printf("%d\n", DAYS_IN_WEEK);
  printf("%f\n", PI);
  return 0;
}

A constant cannot change

This program tries to change LIMIT after fixing it. The compiler stops and says the variable is read-only.

#include <stdio.h>

int main() {
  const int LIMIT = 100;
  LIMIT = 200;
  printf("%d\n", LIMIT);
  return 0;
}

Example

#include <stdio.h>

int main() {
  const int APPLES = 12;
  const int PRICE_EACH = 3;
  int total = APPLES + PRICE_EACH;
  printf("%d\n", total);
  return 0;
}

Key points

  • A constant is a value that stays fixed as the program runs.
  • const in front of a type marks a variable as a constant.
  • const int LIMIT = 100; makes LIMIT hold 100 for the whole program.
  • Constant names use capital letters.
  • An underscore joins words in a constant name, like DAYS_IN_WEEK.
  • A const double holds a fixed decimal number, like PI.

APPLES holds 12 and PRICE_EACH holds 3, and both stay fixed. The program adds them and prints 15.

Note

Changing a constant stops the compile, and the compiler says the variable is read-only.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line makes a constant named MAX that holds 100?