为什么以下两个C代码的输出有所不同? [英] Why the two following C code differ by output?

查看:156
本文介绍了为什么以下两个C代码的输出有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码输出4:

The following code outputs 4:

#include<stdio.h>
int main()
{

    printf("%d",1+(int)NULL);
}



虽然以下代码输出1:



While the following code outputs1:

#include
int main()
{

    printf("%d",1+(int)NULL);
}



我尝试过的事情:

我不明白上面的代码为何不同?



What I have tried:

I don''t understand why the above codes differ differ?

推荐答案

可能是因为stdio.h#如果未定义NULL,则将NULL定义为特定值.
标准VS C ++ stdio.h使用以下代码:
Probably because stdio.h #defines NULL to a specific value if it isn''t defined.
The standard VS C++ stdio.h uses this:
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else  /* __cplusplus */
#define NULL    ((void *)0)
#endif  /* __cplusplus */
#endif  /* NULL */

,但是可以定义一个NULL,但在添加了(int)演员表.而且由于指针+ 1会增加机器字"的大小,因此很可能在32位环境中,结果地址将为4.
首先,请查看您的包含文件的确切内容,并检查它们将NULL定义为的内容(因为未将其定义为C或C ++关键字)

But it would be possible to define a NULL that still ended up as a void pointer after the addition of the (int) cast. And since a pointer + 1 increments by the size of a "machine word", it''s quite likely that in a 32 bit environment, the resulting address would be four.
I''d start by looking at the exact content of your include files and check what they define NULL as (since it isn''t defined as a C or C++ keyword)


这篇关于为什么以下两个C代码的输出有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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