关于暂定定义 [英] About Tentative definition

查看:206
本文介绍了关于暂定定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一本书初步认定中读到,


  

一个试探性的定义是,没有任何外部数据声明
  存储类说明并没有初始化。暂定的定义
  成为一个完整定义如果翻译单元的末端是
  达到并没有定义已经出现了对一个初始化
  标识符


请解释一下上述语句的意思。
此外,声明和定义的区别?我搞混了,由于这一点。 :(
而为什么不这项计划提供了一个错误:

 #包括LT&;&stdio.h中GT;
int类型的; //暂定定义
int类型的; //这同样也声明。
INT主要()//没有得到任何错误与此code为什么它如此?
{
    的printf(HI);
}

此外,什么是错的这个code:

 #包括LT&;&stdio.h中GT;
的printf(你好);
诠释主要(无效){
    返回0;
}


解决方案

一个可变的声明的说,没有与下面的名称和类型程序中的变量。

一个可变的定义的说:亲爱的先生编译,请使用以下名称的变量分配内存,现在打字。

所以可以为同一个变量多次声明,但应该只有一个定义。

在C,纯声明(这是不是也定义)是preceded用关键字的extern 。所以,请你以后不要在你的第一个例子这个关键字,你所拥有的是两个定义。在其表面上,这似乎是一个问题(实际上是在C ++中的错误),但C有一个特殊的暂定定义的规则,它允许多个定义为相同的变量,只要它们所有的匹配和至多一个有一个初始化。 C编译器,在幕后,将所有暂定定义成一个单一的定义。

有了你试图设定两个定义,如:

  int类型的= 1;
int类型的= 2;

然后,你将不得不一个错误。

您的第二个问题是比较简单的。在C语言中,你根本不能有函数体之外的可执行语句。它只是不允许的。想想看:当你期望它运行如果允许

I read from a book about tentative defination that,

A tentative definition is any external data declaration that has no storage class specifier and no initializer. A tentative definition becomes a full definition if the end of the translation unit is reached and no definition has appeared with an initializer for the identifier

Please explain what the above statement means. Also, the difference between Declaration and Definition? I got mixed up due to this. :( And why doesn't this program gives an error:

#include<stdio.h>
int a;      //Tentative definition
int a;      //similarly this declaration too.
int main()  //not getting any error with this code why its so?
{
    printf("hi");
} 

Also, what is wrong with this code:

#include<stdio.h>
printf("Hi");
int main(void){
    return 0;
}

解决方案

A variable declaration says, "there is a variable with the following name and type in the program".

A variable definition says, "Dear Mr. Compiler, please allocate memory for a variable with the following name and type now."

So there can be multiple declarations for the same variable, but there should be only one definition.

In C, pure declarations (that are not also definitions) are preceded with the keyword extern. So, since you do not have this keyword in your first example, what you have is two definitions. On its face, this would seem to be a problem (and is in fact an error in C++), but C has a special "tentative definition" rule which allows multiple definitions for the same variable so long as they all match and at most one has an initializer. The C compiler, behind the scenes, combines all of the tentative definitions into a single definition.

Had you attempted to initialize both definitions, like this:

int a = 1;
int a = 2;

Then you would have had an error.

Your second question is more straightforward. In C, you simply cannot have executable statements outside of the body of a function. It's just not allowed. Think about it: when would you expect it to run if it were allowed?

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

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