Skip to content
Related Articles

Related Articles

Improve Article

Code valid in both C and C++ but produce different output

  • Difficulty Level : Medium
  • Last Updated : 29 Oct, 2018

There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages.

Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++:

Example Codes valid in both C and C++ but give different answers when compiled :




// C code that is valid in both
// C and C++ but produce different
// behavior when compiled.
  
#include <stdio.h>
  
// extern keyword for variable
// declaration without define
extern int S;
  
// function for struct
int differCAndCpp(void)
{
    // create a structure
    struct S {
        int a;
        int b;
    };
  
    // return sizeof integer variable
    return sizeof(S);
}
// Main driver
int main()
{
    // call function differCAndCpp()
    printf("%d", differCAndCpp());
    return 0;
}

Output:



4

Code in C++




// C++ code that is valid in both
// C and C++ but produce different
// behavior when compiled.
  
#include <iostream>
using namespace std;
  
// extern keyword used for variable
// declaration without define
extern int S;
  
// function for struct
int differCAndCpp(void)
{
    // create a structure
    struct S {
        int a;
        int b;
    };
  
    // return sizeof structure
    // in c++
    return sizeof(S);
}
  
// Main driver
int main()
{
    // call function differCAndCpp()
    printf("%d", differCAndCpp());
    return 0;
}

Output:

8

We can see that both the codes are same but outputs are different. This is due to C requiring struct in front of structure tags (and so sizeof(S) refers to the variable), but C++ allowing it to be omitted (and so sizeof(S) refers to the implicit typedef).

Please note that the outcome is different when the extern declaration is placed inside the function: then the presence of an identifier with same name in the function scope inhibits the implicit typedef to take effect for C++, and the outcome for C and C++ would be the same. Observe also that the ambiguity in the example above is due to the use of the parenthesis with the sizeof operator.

Using sizeof T would expect T to be an expression and not a type, and thus the example would not give same result with C++.

Related Article :

Ref:-https://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :