patterncppCritical
Can code that is valid in both C and C++ produce different behavior when compiled in each language?
Viewed 0 times
andproducevalidbehaviorcompiledlanguagewheneachcanthat
Problem
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:
If the versions matter, then please mention which versions of each produce different behavior.
(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.
Solution
The following, valid in C and C++, is going to (most likely) result in different values in
See Why is the size of a character sizeof('a') different in C and C++? for an explanation of the difference.
Another one from this article:
i in C and C++:int i = sizeof('a');
See Why is the size of a character sizeof('a') different in C and C++? for an explanation of the difference.
Another one from this article:
#include
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;
}
Context
Stack Overflow Q#12887700, score: 422
Revisions (0)
No revisions yet.