I am trying to get a sense of how I should use const
in C code. First I didn't really bother using it, but then I saw a quite a few examples of const
being used throughout. Should I make an effort and go back and religiously make suitable variables const
? Or will I just be waisting my time?
I suppose it makes it easier to read which variables that are expected to change, especially in function calls, both for humans and the compiler. Am I missing any other important points?
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero. A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.
Always declare a variable with const when you know that the value should not be changed. Use const when you declare: A new Array. A new Object.
const
is typed, #define
macros are not.
const
is scoped by C block, #define
applies to a file (or more strictly, a compilation unit).
const
is most useful with parameter passing. If you see const
used on a prototype with pointers, you know it is safe to pass your array or struct because the function will not alter it. No const
and it can.
Look at the definition for such as strcpy()
and you will see what I mean. Apply "const-ness" to function prototypes at the outset. Retro-fitting const
is not so much difficult as "a lot of work" (but OK if you get paid by the hour).
Also consider:
const char *s = "Hello World";
char *s = "Hello World";
which is correct, and why?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With