ADVERTISEMENT
ADVERTISEMENT

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?
Submitted by IncludeHelp, on August 23, 2018

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:

#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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.