Lotus@ 2012-10-14 23:54 采纳率: 100%
浏览 359
已采纳

在 c 和 c + + 中都有效的代码在用每种语言编译时会产生不同的行为吗?

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.)

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:

  • 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.

转载于:https://stackoverflow.com/questions/12887700/can-code-that-is-valid-in-both-c-and-c-produce-different-behavior-when-compile

  • 写回答

15条回答 默认 最新

  • 三生石@ 2012-10-14 23:57
    关注

    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');
    

    See Size of character ('a') in C/C++ for an explanation of the difference.

    Another one from this article:

    #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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?