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

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

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

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


当前回答

这涉及到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++.

其他回答

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++中的内联函数则不是。

在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++编程语言(第三版)给出了三个例子:

sizeof('a'),正如@Adam Rosenfield提到的; //注释被用来创建隐藏代码: Int f(Int a, Int b) { 返回a //* blah */ b ; } 结构等隐藏的东西在外部作用域,如在你的例子。

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

#include <stdio.h>

typedef struct {} Foo;

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

int main()
{
    abort();
    return 0;
}

在c++中返回退出码为0,在C中返回退出码为3。

这个技巧可能可以用来做一些更有趣的事情,但我想不出一个好方法来创建一个构造函数,让c满意。我试着用复制构造函数做了一个同样无聊的例子,让一个参数被传递,尽管以一种相当不可移植的方式:

struct exit
{
    int x;
};

int main()
{
    struct exit code;
    code.x=1;

    exit(code);

    return 0;
}

vc++ 2005拒绝在c++模式下编译,但是,抱怨如何重新定义“退出代码”。(我认为这是一个编译器错误,除非我突然忘记了如何编程。)但是当它被编译成C语言时,进程退出码为1。