Error: Assignment of read-only variable in C | Common C program Errors

Here, we will learn how and when error 'assignment of read-only variable in C' occurs and how to fix it?
By IncludeHelp Last updated : March 10, 2024

Error: Assignment of read-only variable in C

Error "assignment of read-only variable in C" occurs, when we try to assign a value to the read-only variable i.e. constant.

In this program, a is a read-only variable or we can say a is an integer constant, there are two mistakes that we have made:

  1. While declaring a constant, value must be assigned – which is not assigned.
  2. We cannot assign any value after the declaration statement to a constant – which we are trying to assign.

Consider the program:

Example

#include <stdio.h>

int main(void) {
    
	const int a;
	a=100;
	
	printf("a= %d\n",a);
	
	return 0;
}

Output

prog.c: In function 'main':
prog.c:6:3: error: assignment of read-only variable 'a'
  a=100;
   ^

How to fix it?

Assign value to the variable while declaring the constant and do not reassign the variable.

Correct Code

#include <stdio.h>

int main(void) {
    
	const int a = 100;
	
	printf("a= %d\n",a);
	
	return 0;
}

Output

a= 100

C Common Errors Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.