使用& (addressof)与C中的const变量 [英] Using & (addressof) with const variables in C

查看:74
本文介绍了使用& (addressof)与C中的const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

教科书上说& (addressof)运算符不适用于无法应用于表达式,
常数或寄存器变量。

常数仅表示诸如'A','7'等常量还是

我认为这只意味着文字,因为以下代码可以编译:-

Text books say that & (addressof) operator doesn't apply to cannot be applied to expressions,
constants, or register variables.
Does constants mean only literals like 'A', '7' etc or variables declared with const keyword as well?
I think this mean only literals since following code compiles:-

int main()
{
const int i=10;
const int *ip;

ip = &i;

}

推荐答案

否-可以将其应用于限定为 const 的变量。但是请注意,这样做(通常)意味着编译器必须实际为该变量分配一个地址-如果仅以不需要地址的方式使用该地址,则使用 const 变量通常根本不需要分配任何存储空间(即,使用 const 变量生成的代码通常几乎就像您使用a直接输入文字,但您的源代码却改用了有意义的名称。)

No -- it can be applied to a variable that's qualified as const. Note, however, that doing so (generally) means that the compiler has to actually assign that variable an address -- if you only use it in ways that don't need an address, a const variable often won't need to be assigned any storage at all (i.e., the code generated using a const variable will often be almost like you'd use a literal directly, but your source code gets to use a meaningful name instead).

这篇关于使用& (addressof)与C中的const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆