c语言中只读变量_错误:在C中分配只读变量| 常见的C程序错误

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是整数常量,我们犯了两个错误:

  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

翻译自: https://www.includehelp.com/c-programs/assignment-of-read-only-variable-in-c.aspx

c语言中只读变量

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值