喵-见缝插针 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条)

报告相同问题?

悬赏问题

  • ¥15 方程如何编到C语言!
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了