Constant Variables in C++

Rishabh Agarwal
3 min readFeb 25, 2023
Photo by Samuel Ferrara on Unsplash

It is almost inevitable to avoid constants in programmes. Whether it’s the usage of constant PI in a mathematical programme or the timeout seconds in an application for user authentication. Various programming languages give varying levels of support for storing and maintaining these constants. In this blog article, we will look at how constants are supported in C++.

Notion of Const-ness in C

Readers with a background in C programming language would be familiar with the usage of Manifest constants for storing constants. For others, here is a code example of how manifest constants are defined and used in C.

#include <stdio.h>

#define PI 3.14 // Manifest constant defining PI

float area(float radius) {
// C PreProcessor will replace PI with 3.14 before compiling
return PI * radius * radius;
}

int main() {
printf("%f\n", area(5.0));
}

These manifest constants looks like variable but are actually not. Compiler treats these constants as symbols which are replaced by C Pre-Processor.

There are several inherent problems with manifest constants, like —

  • No type checking.
  • No name scoping. Everything is global.
  • Risk of naming conflicts.
  • Cannot be watched in debugger.

--

--

Rishabh Agarwal

Software Developer 2 @ Schrödinger | IIT CSE Graduate - Writes about Software Engineering!