TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Can code that is valid in both C and C++ produce different behavior?

83 点作者 ivoflipse超过 12 年前

3 条评论

CJefferson超过 12 年前
Interesting discussion. I can honestly say that I have never seen any of these come up.<p>In case anyone is worried, the sizeof('i') one looks, at first glance, like the most worrying one.<p>However, it is less serious than it might look. Given "char c;", sizeof(c) evaluates to 1 in both languages, it is just a single character constant like 'i' which causes a possible problem.<p>For anyone curious why, I'm not sure why character constants are int in C, but in pure C I think it is impossible to tell that a character literal is an int (as there is no function overloading, or type deductions).<p>In C++ however, with function overloading, we can tell. In particular, we really want:<p>std::cout &#60;&#60; 1 &#60;&#60; 'i' &#60;&#60; std::endl;<p>To print the number 1, followed by the letter i. Therefore we need the letter i to be of type char, rather than another int.<p>(Fixed last 'C' to 'C++' : Thanks dbaupp)
评论 #4654322 未加载
评论 #4654234 未加载
finnw超过 12 年前
It's nice to see a HN submission of an <i>on-topic</i> stackoverflow question (instead of all the off-topic ones that get submitted, followed by comments complaining about the question being closed on SO.)
sturmeh超过 12 年前
I'm sure you could get different behaviours with some fancy use of pointers and reference notation.