Const qualifiers are used to specify how a value can change, if at all. You can write your code without ever using a const qualifier, but using them will help protect values from being changed in a way you didn’t intend.
Using Const with Primitives Types
The first and most basic way to use const is to use it with primitive types.
int main()
{
const int num = 5;
num = 4;
return 0;
}
Try to compile this. You will get an error that resembles something like the following:
prog.c: In function 'main': prog.c:5:14: error: assignment of read-only variable 'num' num = 4; ^
Your compiler threw an error because you specified that you wanted num to be a constant. Because the compiler saw the const qualifier, when we tried to reassign num, it knew you were trying to change a constant. Had we not declared int as a const, your compiler would have no idea that num was supposed to be a constant.
Using Const with Pointers
Using const qualifiers with pointers is a bit more complicated. There are 4 options:
<type> * – The pointer address can be reassigned, and the value at that address can also be changed.
int num = 5;
int num2 = 6;
int * ptr = #
ptr = &num2; // This is perfectly legal
*ptr = 4; // This is also legal
const <type> * – The pointer address can be reassigned, but the value at that address cannot be changed.
int num = 5;
int num2 = 6;
const int * ptr = #
ptr = &num2; // This is perfectly legal
*ptr = 4; // Illegal, cannot modify the value in the block
<type> * const – The pointer address cannot be changed, but the memory block it points to can be modified.
int num = 5;
int num2 = 6;
int * const ptr = #
ptr = &num2; // Illegal, we cannot reassign the pointer
*ptr = 4; // Legal, we can modify the value in the block
const <type> * const – Nothing can be changed.
int num = 5;
int num2 = 6;
const int * const ptr = #
ptr = &num2; // Illegal, we cannot reassign the pointer
*ptr = 4; // Illegal, cannot modify the value in the block
If that didn’t make sense, that’s fine, there is a helpful table for us to reference below:
int * | const int * | int * const | const int * const | |
ptr = | yes | yes | no | no |
*ptr = | yes | no | yes | no |