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
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.
- Results of comparison operations in C and C++
- Write a C program to print "GfG" repeatedly without using loop, recursion and any control structure?
- Write a C program to print "Geeks for Geeks" without using a semicolon
- Write a C program that does not terminate when Ctrl+C is pressed
- Write a C program that won't compile in C++
- Write a URL in a C++ program
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C program to write an image in PGM format
- Write one line functions for strcat() and strcmp()
- Write your own memcpy() and memmove()
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- Write a one line C function to round floating point numbers
- Write a C macro PRINT(x) which prints x
- When should we write our own copy constructor?
- Does C++ compiler create default constructor when we write our own?
- When should we write our own assignment operator in C++?
- fopen() for an existing file in write mode
- How to write a running C code without main()?
- How to write long strings in Multi-lines C/C++?
- Write your own strlen() for a long string padded with '\0's