Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I best use the const keyword in C?

Tags:

c

constants

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?

like image 566
c00kiemonster Avatar asked Jan 18 '13 15:01

c00kiemonster


People also ask

How is const used in C?

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.

Why should I use const in C?

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.

What is the correct way to declare constants C?

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.

When should I use const?

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.


1 Answers

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?

like image 67
cdarke Avatar answered Oct 11 '22 13:10

cdarke