Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers.
There can be many such programs, following are some of them.
1) Character literals are treated differently in C and C++. In C character literals like ‘a’, ‘b’, ..etc are treated as integers, while as characters in C++. (See this for details)
For example, the following program produces sizeof(int) as output in C, but sizeof(char) in C++.
2) In C, we need to use struct tag whenever we declare a struct variable. In C++, the struct tag is not necessary. For example, let there be a structure for Student. In C, we must use ‘struct Student‘ for Student variables. In C++, we can omit struct and use ‘Student‘ only.
Following is a program that is based on the fact and produces different outputs in C and C++. It prints sizeof(int) in C and sizeof(struct T) in C++.
3) Types of boolean results are different in C and C++. Thanks to Gaurav Jain for suggesting this point.
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Difference between C structures and C++ structures
- Namespace in C++ | Set 1 (Introduction)
- Commonly Asked C++ Interview Questions | Set 2
- Basic Concepts of Object Oriented Programming using C++
- Commonly Asked OOP Interview Questions | Set 1
- Commonly Asked C++ Interview Questions | Set 1
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- Can we access private data members of a class without using a member or a friend function?
- Write a C program that won't compile in C++
- Name Mangling and extern "C" in C++
- References in C++
- Type difference of character literals in C and C++
- "delete this" in C++
- Data type of character constants in C and C++
- How does "void *" differ in C and C++?