我在 Compiler Exporer 中编译了以下 C 代码查看它如何处理 const
关键字:
int a=1;
const b=2;
int func () {
int c=3;
const int d=4;
}
.section .data
a:
.long 1
.section .rodata
b:
.long 2
func:
pushq %rbp
movq %rsp, %rbp
movl $3, -4(%rbp)
movl $4, -8(%rbp)
nop # also, why does it add a nop here?
popq %rbp
ret
据我所知,对于在函数外部定义的变量(文件全局),它会在顶部添加一个标签。但是,如果它是 const 变量,则顶部的变量将放置在只读部分中。我的问题是针对以下局部变量:
const int d=4;
它的“常量”是如何管理的,因为它只是堆栈上的一个值,并且堆栈上的任何值都不能自由修改?或者,在汇编中,是否不存在常量局部变量之类的东西,而这只是编译器强制执行的概念?
最佳答案
试试吧。
int fun ( void )
{
const int d=4;
return(d);
}
00000000 <fun>:
0: e3a00004 mov r0, #4
4: e12fff1e bx lr
int fun ( void )
{
const int d=4;
return(d);
}
int fun1( void )
{
int d=4;
d=5;
return(d);
}
int fun2 ( void )
{
const int d=4;
d=5;
return(d);
}
so.c: In function ‘fun2’:
so.c:16:6: error: assignment of read-only variable ‘d’
int fun ( void )
{
const int d=4;
return(d);
}
int fun1( void )
{
int d=4;
d=5;
return(d);
}
00000000 <fun>:
0: e3a00004 mov r0, #4
4: e12fff1e bx lr
00000008 <fun1>:
8: e3a00005 mov r0, #5
c: e12fff1e bx lr
全局变量是全局变量,在某个段中获取内存分配,局部变量是局部变量,除非声明为静态(局部全局变量),否则它们位于堆栈或寄存器中。 Const 只是向编译器表明它可以基于变量只读而不是读/写的假设来生成代码。如果您尝试写入只读声明的变量,更好的编译器会提示。所以 const int 和 int 之间的区别是只读和读/写。
关于汇编中局部和全局范围内的 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63643768/