喵-见缝插针 2012-10-14 23:54 采纳率: 0%
浏览 204
已采纳

在 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

  • 写回答

16条回答 默认 最新

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

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制