Write a C program that won’t compile in C++
Although C++ is designed to have backward compatibility with C, there can be many C programs that would produce compiler errors when compiled with a C++ compiler. Following is the list of the C programs that won’t compile in C++:
- Calling a function before the declaration
- Using normal pointer with const variable
- Using typecasted pointers
- Declaring constant values without initializing
- Using specific keywords as variable names
- Strict type checking
- The return type of main()
These points are discussed in detail below:
1) Calling a function before declaration: In C++, it is a compiler error to call a function before it is declared. But in C, it may compile. (See What happens when a function is called before its declaration in C?)
2) Using a normal pointer with const variable: In C++, a compiler error is generated when a normal pointer is used to point to a const variable, however, it is allowed in C. (Must Read – Const Qualifier in C)
3) Using typecasted pointers: In C, a void pointer can directly be assigned to some other pointer like int *, char *. But in C++, a void pointer must be explicitly typed cast.
Note: This is something we notice when we use malloc(). Return type of malloc() is void *. In C++, we must explicitly typecast return value of malloc() to appropriate type, e.g., “int *p = (int *)malloc(sizeof(int))”. In C, typecasting is not necessary.
4) Declaring constant values without initializing: In C++, the const variable must be initialized but in C it is not necessary. The following program compiles & runs fine in C, but fails in the compilation in C++.
5) Using specific keywords as variable names: In C, specific keywords can be used as variable names, however, it is not possible in C++. The following program won’t compile in C++ but would compile in C.
Similarly, we can use other keywords like delete, explicit, class, etc.
6) Strict type checking: C++ does more strict type checking than C. For example, the following program compiles in C, but not in C++. In C++, we get compiler error “invalid conversion from ‘int’ to ‘char*'”.
7) Return type of main(): In C++, the main function requires the return type of ‘int’, however not the case in C. In C++, we cannot use the return type as ‘void’.
8) The following program compiles in C but doesn’t compile in C++. (See this article for more reference.)
Explanation: In C++, func() is equivalent to func(void), however in C, func() is equivalent to func(…).
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
Please Login to comment...