Utilizor
Contact Us
HomeC TutorialC Constants

CC Constants

Unchangeable variables.

C Constants

If you don't want others (or yourself) to override existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only).

It is considered good practice to declare constants with uppercase.

Examples

Const Keyword

c example

Defining a constant.

#include <stdio.h>

int main() {
  const int MYNUM = 15;  // myNum will always be 15
  // MYNUM = 10;  // error: assignment of read-only variable 'MYNUM'
  
  printf("%d", MYNUM);
  return 0;
}

Constant Calculation

c example

Using constants in math.

#include <stdio.h>

int main() {
  const float PI = 3.14;
  const int RADIUS = 10;
  float area = PI * RADIUS * RADIUS;
  
  printf("Area: %f", area);
  return 0;
}

Test Your Knowledge

1. Which keyword makes a variable read-only?

2. What happens if you try to change a const variable?