DEV Community

Kshitij Srivastava
Kshitij Srivastava

Posted on • Edited on

Using Const

An important factoring in understanding your code is realising what is mutable and when. Often times, variables we use in code do not need to change or, should not be changed.

C uses the const keyword to signify that a variable cannot be mutated. You may have seen this when making strings, const char*.

But, using const brings up the important discussion of mutability in programs, leading to large online debates about the essence of programming.

There are those who believe that code is nothing but mathematics and such, should not have mutable state at all. Once a variable is declared and initialised, its value cannot and should not change.

On the other side, there are those who say that this approach only works on white-papers and technical documents and that in the real world, with real-time communication to databases and APIs, it is nearly impossible to write pure code.

In any case, realising the importance of constant values is important as a programmer and using const for such values encourages writing cleaner code.

While using const rarely has any performance benefits, it is important to consider its benefits on developer experience. const enforces the idea of constants as opposed to being left as overhead to the programmer.

// Constant parameters.
void do_something(const int data) {
    ...
}

int main(void) {
    // Constant local variables.
    const int number = 5;

    // Constant pointers.
    const char* message = "Hello, world!\n";

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)