可以code,它是有效的,在每一种语言进行编译时C和C ++产生不同的行为呢? [英] Can code that is valid in both C and C++ produce different behavior when compiled in each language?
问题描述
C和C ++有许多不同,并不是所有的有效C code是有效的C ++ code。结果
(通过有效我的意思是标准的code。与定义的行为,即没有实现特定的/不确定的/ etc。)
C and C++ have many differences, and not all valid C code is valid C++ code.
(By "valid" I mean standard code with defined behavior, i.e. not implementation-specific/undefined/etc.)
有没有这两个C和C ++有效一块code会产生任何情况下的不同的的行为时,在每种语言标准的编译器编译?
Is there any scenario in which a piece of code valid in both C and C++ would produce different behavior when compiled with a standard compiler in each language?
要使它成为一个合理的/有用的比较(我想学的东西实际有用的,不要试图找到问题的明显漏洞),我们假设:
To make it a reasonable/useful comparison (I'm trying to learn something practically useful, not to try to find obvious loopholes in the question), let's assume:
- 没什么preprocessor相关的(这意味着
的#ifdef __cplusplus
没有黑客,语法等) - 任何实现定义是在两种语言相同(例如数字的限制,等等。)
- 我们所比较的各标准的合理最新版本(例如说,C ++ 98和C90或更高版本)结果
如果版本无所谓,那么请注明每个版本产生不同的行为。
- Nothing preprocessor-related (which means no hacks with
#ifdef __cplusplus
, pragmas, etc.) - Anything implementation-defined is the same in both languages (e.g. numeric limits, etc.)
- We're comparing reasonably recent versions of each standard (e.g. say, C++98 and C90 or later)
If the versions matter, then please mention which versions of each produce different behavior.
推荐答案
以下,在C和C ++,是要(最有可能)会导致不同的值 I $ C $有效C> C和C ++:
The following, valid in C and C++, is going to (most likely) result in different values in i
in C and C++:
int i = sizeof('a');
请参阅字符('A')中的C / C ++ 的大小为差异的解释
See Size of character ('a') in C/C++ for an explanation of the difference.
更新: 另一位这篇文章:
#include <stdio.h>
int sz = 80;
int main(void)
{
struct sz { char c; };
int val = sizeof(sz); // sizeof(int) in C,
// sizeof(struct sz) in C++
printf("%d\n", val);
return 0;
}
这篇关于可以code,它是有效的,在每一种语言进行编译时C和C ++产生不同的行为呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!