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 :
Code in C++
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 :
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to bind 'touchstart' and 'click' events but not respond to both ?
- Use of & in scanf() but not in printf()
- Publicly inherit a base class but making some of public method as private
- Hide scroll bar, but while still being able to scroll using CSS
- Difference between Fastag, Bar Code, QR Code and NFC
- Difference between QR Code, Bar Code and NFC
- Difference between Source Code and Object Code
- Difference Between Source Code and Byte Code
- Difference between Byte Code and Machine Code
- Different Python IDEs and Code Editors
- Java Program to Convert Binary Code Into Equivalent Gray Code Using Recursion
- Execute both if and else statements in C/C++ simultaneously
- Why to check both isset() and !empty() function in PHP ?
- Count numbers upto N which are both perfect square and perfect cube
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- What does the CSS rule “clear: both” do?
- Programming vs Coding - A Short Comparison Between Both
- Solve Linear Equations with Variable on both Sides
- What happen when we exceed valid range of built-in data types in C++?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ankit15697