C语言中的声明与定义 [英] Declaration vs definition in C

查看:74
本文介绍了C语言中的声明与定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码:

int main(void)
{
    int a;
}

据我所知,int a;是一个定义,因为它会导致存储被保留.引用C标准(N1570委员会草案,2011年4月12日):

As far as I know, int a; is a definition, as it causes storage to be reserved. Citing the C standard (N1570 Committee Draft — April 12, 2011):

6.7/5语义学 声明指定一组标识符的解释和属性.标识符的定义是对该标识符的声明:

6.7/5 Semantics A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

-对于一个对象,导致为该对象保留存储空间;

— for an object, causes storage to be reserved for that object;

...

这里是一个问题:由于我们没有使用变量,因此编译器可能会优化存储空间.那么int a;是一个声明吗?还有,如果我们在main(void)中执行printf("%p", &a)怎么办-肯定现在编译器必须分配存储空间,所以声明/定义的概念是否取决于您以后是否使用标识符?

Here comes the question: the compiler may optimize away the storage, since we are not using the variable. Is then int a; a declaration then? And what if we do a printf("%p", &a) in main(void) - certainly now the compiler has to allocate storage, so is the concept of declaration/definition dependent on whether you later use the identifier or not?

推荐答案

您在6.7/5中引用的文本实际上是用来解释您所做的事情的:被分配.

The text you quoted from 6.7/5 is actually meant to be interpreted the other way around than what you have done: the text is saying that definitions cause storage to be allocated.

用于指定int a;是定义的文本在其他位置.

The text which specifies that int a; is a definition is elsewhere.

C是根据抽象机定义的.在抽象机中分配了存储.在计算机上是否分配了任何内存都无关紧要.

C is defined in terms of an abstract machine. There is storage allocated in the abstract machine. Whether or not any memory is allocated on your PC is unrelated.

这篇关于C语言中的声明与定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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