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

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

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

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


当前回答

这个程序在c++中输出1,在C中输出0:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int d = (int)(abs(0.6) + 0.5);
    printf("%d", d);
    return 0;
}

这是因为在c++中有双abs(double)重载,所以abs(0.6)返回0.6,而在C中它返回0,因为在调用int abs(int)之前,它是隐式的双到整型转换。在C语言中,你必须使用fab与double一起工作。

其他回答

不要忘记C和c++全局名称空间之间的区别。假设你有一个foo。cpp

#include <cstdio>

void foo(int r)
{
  printf("I am C++\n");
}

和foo2.c

#include <stdio.h>

void foo(int r)
{
  printf("I am C\n");
}

现在假设你有一个main.c和main.cpp,它们看起来都是这样的:

extern void foo(int);

int main(void)
{
  foo(1);
  return 0;
}

当编译为c++时,它将使用c++全局命名空间中的符号;在C中,它将使用C:

$ diff main.cpp main.c
$ gcc -o test main.cpp foo.cpp foo2.c
$ ./test 
I am C++
$ gcc -o test main.c foo.cpp foo2.c
$ ./test 
I am C

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是默认值。

#include <stdio.h>

struct A {
    double a[32];
};

int main() {
    struct B {
        struct A {
            short a, b;
        } a;
    };
    printf("%d\n", sizeof(struct A));
    return 0;
}

这个程序在使用c++编译器编译时输出128 (32 * sizeof(double)),在使用C编译器编译时输出4。

这是因为C语言没有范围解析的概念。在C语言中,包含在其他结构中的结构被放到外部结构的范围内。

c++标准中列出的另一个:

#include <stdio.h>

int x[1];
int main(void) {
    struct x { int a[2]; };
    /* size of the array in C */
    /* size of the struct in C++ */
    printf("%d\n", (int)sizeof(x)); 
}
int main(void) {
    const int dim = 5; 
    int array[dim];
}

这是相当奇怪的,因为它在c++和C99, C11和C17中是有效的(尽管在C11, C17中是可选的);但在C89中无效。

在C99+中,它创建了一个变长数组,与普通数组相比,它有自己的特性,因为它是运行时类型而不是编译时类型,并且sizeof数组在C中不是整数常量表达式。在c++中,该类型完全是静态的。


如果你尝试在这里添加初始化式:

int main(void) {
    const int dim = 5; 
    int array[dim] = {0};
}

是有效的c++,但不是C,因为变长数组不能有初始化式。