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.
当我们尝试为只读变量(即常量)分配值时,发生错误“在C中分配只读变量”。
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:
在此程序中, a是只读变量,或者我们可以说a是整数常量,我们犯了两个错误:
While declaring a constant, value must be assigned – which is not assigned.
在声明常量时,必须分配值-未分配。
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
翻译自: https://www.includehelp.com/c-programs/assignment-of-read-only-variable-in-c.aspx
c语言中只读变量