C和c++有很多不同之处,并不是所有有效的C代码都是有效的c++代码。 (这里的“有效”指的是具有定义行为的标准代码,即不是特定于实现的/未定义的/等等。)

在哪种情况下,一段在C和c++中都有效的代码在使用每种语言的标准编译器编译时会产生不同的行为?

为了做一个合理/有用的比较(我试图学习一些实际有用的东西,而不是试图在问题中找到明显的漏洞),让我们假设:

与预处理器无关(这意味着没有使用#ifdef __cplusplus、pragmas等进行hack) 在这两种语言中,任何实现定义都是相同的(例如数字限制等)。 我们比较每个标准的最新版本(例如,c++ 98和C90或更高版本) 如果版本很重要,那么请说明每个版本会产生不同的行为。


当前回答

C90 vs. c++ 11 (int vs. double)

#include <stdio.h>

int main()
{
  auto j = 1.5;
  printf("%d", (int)sizeof(j));
  return 0;
}

在C语言中,auto表示局部变量。在C90中,可以省略变量或函数类型。它默认为int。在c++ 11中,auto的意思完全不同,它告诉编译器从用于初始化变量的值推断变量的类型。

其他回答

下面是一个例子,它利用了C和c++中函数调用和对象声明之间的差异,以及C90允许调用未声明的函数的事实:

#include <stdio.h>

struct f { int x; };

int main() {
    f();
}

int f() {
    return printf("hello");
}

在c++中,这不会打印任何东西,因为创建和销毁了一个临时f,但在C90中,它会打印hello,因为函数可以在没有声明的情况下被调用。

如果你想知道名称f被使用了两次,C和c++标准明确地允许这样做,并且要创建一个对象,如果你想要结构,你必须说struct f来消除歧义,或者如果你想要函数,就不要struct。

#include <stdio.h>

int main(void)
{
    printf("%d\n", (int)sizeof('a'));
    return 0;
}

在C语言中,这将打印当前系统中sizeof(int)的值,在目前使用的大多数系统中,这通常是4。

在c++中,这必须打印1。

空结构体的大小在C中为0,在c++中为1:

#include <stdio.h>

typedef struct {} Foo;

int main()
{
    printf("%zd\n", sizeof(Foo));
    return 0;
}

C中的内联函数默认为外部作用域,而c++中的内联函数则不是。

在GNU C中,将下面两个文件编译在一起将打印“I am inline”,而在c++中则没有。

文件1

#include <stdio.h>

struct fun{};

int main()
{
    fun();  // In C, this calls the inline function from file 2 where as in C++
            // this would create a variable of struct fun
    return 0;
}

文件2

#include <stdio.h>
inline void fun(void)
{
    printf("I am inline\n");
} 

此外,c++隐式地将任何const全局变量视为静态的,除非显式地声明了extern,不像C中extern是默认值。

这涉及到C和c++中的左值和右值。

在C编程语言中,加前和加后操作符都返回右值,而不是左值。这意味着它们不能在=赋值操作符的左边。这两个语句都会在C语言中产生编译器错误:

int a = 5;
a++ = 2;  /* error: lvalue required as left operand of assignment */
++a = 2;  /* error: lvalue required as left operand of assignment */

然而,在c++中,前自增操作符返回左值,而后自增操作符返回右值。这意味着带有预增量操作符的表达式可以放在=赋值操作符的左侧!

int a = 5;
a++ = 2;  // error: lvalue required as left operand of assignment
++a = 2;  // No error: a gets assigned to 2!

为什么会这样呢?后增量函数对变量进行递增,并返回该变量在递增发生之前的状态。这实际上就是一个右值。变量a的前一个值作为临时值复制到寄存器中,然后对a进行递增。但是a的前一个值是由表达式返回的,它是一个右值。它不再表示变量的当前内容。

The pre-increment first increments the variable, and then it returns the variable as it became after the increment happened. In this case, we do not need to store the old value of the variable into a temporary register. We just retrieve the new value of the variable after it has been incremented. So the pre-increment returns an lvalue, it returns the variable a itself. We can use assign this lvalue to something else, it is like the following statement. This is an implicit conversion of lvalue into rvalue.

int x = a;
int x = ++a;

由于预增量返回一个左值,我们也可以给它赋值。下面两种说法是相同的。在第二次赋值中,首先对a进行递增,然后用2覆盖它的新值。

int a;
a = 2;
++a = 2;  // Valid in C++.