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.
Best Answer
Here is an example that takes advantage of the difference between function calls and object declarations in C and C++, as well as the fact that C90 allows the calling of undeclared functions:
In C++ this will print nothing because a temporary
f
is created and destroyed, but in C90 it will printhello
because functions can be called without having been declared.In case you were wondering about the name
f
being used twice, the C and C++ standards explicitly allows this, and to make an object you have to saystruct f
to disambiguate if you want the structure, or leave offstruct
if you want the function.