Q:

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

belongs to collection: C Common Errors Programs

0

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

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Error: \'else\' without a previous \... >>
<< Error: Assign string to the char variable in C | C...