C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

const in c programming

Here, we are discussing about the const, what is const and how it works in c programming language?

First thing to remember const is not a variable, it’s an identifier that identify a constant value. But the word 'const' is a keyword in c programming language that makes an identifier constant. We can change the value of it’s at run time.






Consider these two declarations

    int value1=10;
    const int value2=20;

Here, value1 is an integer variable, the value of value1 can be changed any time at run time. But the value2 is an integer constant, and the value of value2 cannot be changed at run time.

value1 is an integer variables while value2 is an integer constant.

Does a constant occupy memory?

Yes, a constant always occupies memory at compile time. In the above statements, value2 will take sizeof(int) bytes (that may be 2, 4 or 8 according to the system architecture) in the memory.

Let’s consider this example

#include <stdio.h>

int main()
{
	const int value2=20;
	printf("Value of value2: %d\n",value2);
	return 0;
}

Output

    Value of value2: 20

Here, value2 is an integer constant and value of value2 is 20.

What does happen, if we try to change the value of a constant?

If we try to change the value of a constant, compiler produces an error that constant is read only.

Let’s consider this example

#include <stdio.h>

int main()
{
	const int value2=20;
	printf("Value of value2: %d\n",value2);
	value2=30;
	printf("Value of value2: %d\n",value2);
	return 0;
}

Output

    main.c:7:2: error: assignment of read-only variable 'value2'  
      value2=30;  
      ^  

When program is compiled, compiler returned the above error at the line number 7 where we tried to the assign a new value to the value2.


COMMENTS