What is the best way to use the const keyword in C?

I am trying to understand how I should use const in C code. At first I really did not bother to use it, but then I saw quite a few examples of using const . Should I make an effort and come back and religiously make suitable const variables? Or am I just leaving my time?

I believe this makes it easier to read variables that are expected to change, especially in function calls, for both people and the compiler. Are there any other important points?

+6
source share
3 answers

const , #define macros are not.

const has scope C, #define is applied to the file.

const most useful when passing parameters. If you see const used in a prototype with pointers, you know that it is safe to pass your array or structure because the function will not change it. There is no const , and he can.

Take a look at the strcpy() type definition and you will see what I mean. Apply "constness" to run prototypes from the start. Retro-fitting const not as complicated as "a lot of work" (but it's good if you get paid by the clock).

Also consider:

 const char *s = "Hello World"; char *s = "Hello World"; 

what is right and why?

+5
source
 How do I best use the const keyword in C? 

Use const if you want to make it read-only . It's simple:)

+6
source

Using const is not only good practice, but also improves the readability and comprehensibility of the code, and also helps prevent some common mistakes. Definitely use const if necessary.

+1
source

All Articles