DEV Community

Cover image for How constant is const in C?
Matt Ellen-Tsivintzeli
Matt Ellen-Tsivintzeli

Posted on • Edited on

How constant is const in C?

Let's look at the simple statement

const int a = 2;
Enter fullscreen mode Exit fullscreen mode

If you come from a C# perspective, you expect the keyword const to mean that the value in a will never change. It's a way to help the compiler optimise the code.

In C, however, const is not exactly what you would expect.
For sure if you later wrote

a = 4;
Enter fullscreen mode Exit fullscreen mode

then the compiler will throw an error, something along the lines of:

error: assignment of read-only variable ‘a’

But the thing is, this is C, so if you want to shoot yourself in the foot, you can quite easily do it.

(In C# it is possible to change the value of a const with reflection, or unsafe code. It's a fair amount of code, but it can be done.)

This is all the work it takes:

#include <stdio.h>
int main()
{
  const int a = 2;
  printf("a: %d\n", a);
  int* x = &a;
  *x = 4;
  printf("a: %d\n", a);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Just like that. Create a pointer, give it the address of your constant and set the value via the pointer.

Now, depending on the compiler, and your compiler options, you will likely get a warning, something like:

warning: initialization discards ‘const’ qualifier from pointer target type

So, it doesn't go by unnoticed, but it compiles and the code will run just fine.

This is part of the reason I use #define for constants. The other is it's just what I've always done.

I think, for C, it's helpful to think of const as only referring to the variable name, and not the data behind the variable. It's akin to a promise that the variable won't be used to change the value, and not that the value will never change.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More