The Wayback Machine - https://web.archive.org/web/20241127234559/https://www.geeksforgeeks.org/write-a-c-program-that-wont-compile-in-cpp/
Open In App

Write a C program that won’t compile in C++

Last Updated : 22 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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++:

  1. Calling a function before the declaration
  2. Using normal pointer with const variable
  3. Using typecasted pointers
  4. Declaring constant values without initializing
  5. Using specific keywords as variable names
  6. Strict type checking
  7. 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?) 

C




// C Program to demonstrate calling
// a function before declaration
#include <stdio.h>
  
// Main starts
int main()
{
    // fun() is called before its
    // declaration/definition
    fun();
}
  
// Function Declaration
int fun()
{
    printf("Hello");
    return 0;
}


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) 
 

C




// C Program to demonstrate using a
// normal pointer with const variable
#include <stdio.h>
  
// Main starts
int main()
{
  
    // A normal pointer points to const
    int const j = 20;
  
    int* ptr = &j;
  
    // The below assignment is invalid in C++,
    // results in error.In C, the compiler may
    // throw a warning, but casting is implicitly allowed
    printf("*ptr: %d\n", *ptr);
  
    return 0;
}


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. 

C




// C Program to demonstrate
// using typecasted pointers
#include <stdio.h>
  
// Main starts
int main()
{
    void* vptr;
  
    // In C++, it must be
    // replaced with int *iptr=(int *)vptr;
    int* iptr = vptr;
  
    return 0;
}


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++. 

C




// C Program to demonstrate declaring
// constant values without initializing:
#include <stdio.h>
  
// Main starts
int main()
{
    const int a;   
    return 0;
}


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.  

C




// C Program to demonstrate using
// specific keywords as variable names
#include <stdio.h>
  
// Main starts
int main(void)
{
  
    // new is a keyword in C++
    // but not in C
    int new = 5;
  
    printf("%d", new);
}


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*'”. 
 

C




// C Program to demonstrate
// strict type checking
#include <stdio.h>
  
// Main starts
int main()
{
    char *c = 333;
    printf("c = %u", c);
    return 0;
}


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’.

C




// C Program to demonstrate that
// 'void' can be used as a return type
// for main()
#include <stdio.h>
  
// Main starts
void main()
{
    printf("Hello World");
}


8) The following program compiles in C but doesn’t compile in C++. (See this article for more reference.) 

C




// C Program that won't compile in C++
#include <stdio.h>
void func()
{
    // definition
}
  
// Main starts
int main()
{
    func();
    func(2);
}


Explanation: In C++, func() is equivalent to func(void), however in C, func() is equivalent to func(…).



Previous Article
Next Article

Similar Reads

How to compile 32-bit program on 64-bit gcc in C and C++
Mostly compiler(gcc or clang) of C and C++, nowadays come with default 64-bit version. Well it would be a good option in terms of speed purposes. But it would lead to problem, if someone wants to run their program as a 32-bit rather than 64-bit for testing or debugging purposes. Therefore we must have a knowledge about this.Before proceeding forwar
2 min read
VS Code | Compile and Run in C++
In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in
3 min read
How To Compile And Run a C/C++ Code In Linux
C Programming Language is mainly developed as a system programming language to write kernels or write an operating system. C++ Programming Language is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance. In this article, we will be compiling and executing the C Programming Language codes and also C
3 min read
Difference Between Compile Time And Run Time Polymorphism In C++
In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++. What is Polymorphism? Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms. For example, Your DAD is your father. He's your mom's Husband. He's your grandma's son
4 min read
How to Determine if a Type is an STL Container at Compile Time?
In C++, Standard Template Library (STL) provides many containers such as std::vector, std::list, std::map, and more. What if we want to write a generic code that behaves differently when a given type is an STL container? To do this we need to determine at compile time whether a given type is an STL container or not. In this article, we will learn d
6 min read
Write a URL in a C++ program
Writing URLs in programming code doesn't affect the program and the compiler will not throw any error. Here, we will how to use Url in various languages without any errors. The full form of URL is Uniform Resource Locators. URLs are unique they store the address of a particular web application. C/C++ Code // C++ program to demonstrate URL in code #
2 min read
Write a C program to print "Geeks for Geeks" without using a semicolon
First of all we have to understand how printf() function works. Prototype of printf() function is: int printf( const char *format , ...) Parameter format: This is a string that contains a text to be written to stdout.Additional arguments: ... (Three dots are called ellipses) which indicates the variable number of arguments depending upon the format
2 min read
Write a C program that does not terminate when Ctrl+C is pressed
Write a C program that doesn't terminate when Ctrl+C is pressed. It prints a message "Cannot be terminated using Ctrl+c" and continues execution. We can use signal handling in C for this. When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler. C standard defines following 6 signals in signal.
2 min read
Write a program that produces different results in C and C++
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
2 min read
Write a C program that displays contents of a given file like 'more' utility in Linux
Write a C program that displays contents of given line page by page. Given number of lines to show as 'n' at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on. We strongly recommend to minimize the browser and try this yourself first. We can open the given file and p
2 min read
Write a C program to print "GfG" repeatedly without using loop, recursion and any control structure?
As we all know the concept of printing the given string repeatedly using various loops(for loop,while loop),recursion and some control structure also. But the question is how we will print the given string repeatedly i.e. infinitely without using any loops,recursion and any control structure? Examples: Input : GFG Output : GFGGFGGFGGFG...(It will p
1 min read
Write a one line C function to round floating point numbers
Algorithm: roundNo(num) 1. If num is positive then add 0.5. 2. Else subtract 0.5. 3. Type cast the result to int and return. Example: num = 1.67, (int) num + 0.5 = (int)2.17 = 2 num = -1.67, (int) num - 0.5 = -(int)2.17 = -2 Implementation: /* Program for rounding floating point numbers */ # include<stdio.h> int roundNo(float num) { return nu
1 min read
Write a C macro PRINT(x) which prints x
At the first look, it seems that writing a C macro which prints its argument is child's play. Following program should work i.e. it should print x C/C++ Code #define PRINT(x) (x) int main() { printf("%s", PRINT(x)); return 0; } But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unkn
1 min read
Write one line functions for strcat() and strcmp()
Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp(). /* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data is copied using (*dest++ = *src++)? my_strcat(dest, s
2 min read
How to Write Your Own printf() in C?
In this article, we will learn how to implement your own custom printf() function in C language. The printf() function is present in <stdio.h> header and uses a const char* and variable length arguments as its parameters. Hence we would be using <stdarg.h> header file which provides operations available on variable arguments passed to a
4 min read
RapidJSON - File Read/Write in C++
RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data. It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes support for parsing and generating JSON in a strea
6 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a
3 min read
fopen() for an existing file in write mode
In C, fopen() is used to open a file in different modes. To open a file in write mode, "w" is specified. When mode "w" is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the
2 min read
How to write a running C code without main()?
Write a C language code that prints GeeksforGeeks without any main function. Logically it's seems impossible to write a C program without using a main() function. Since every program must have a main() function because:- It's an entry point of every C/C++ program.All Predefined and User-defined Functions are called directly or indirectly through th
2 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include<stdio.h> int main() { // We can put two double quotes anywhere in a string char
2 min read
Write your own strlen() for a long string padded with '\0's
Given a big character array that represents a string such that all trailing non-string characters are filled with '\0' at the end, i.e, all leading characters are string characters, all trailing are '\0' and no garbage characters. Write an efficient function to find length of such a string. Examples: Input: str[] = {'g', 'e', 'e', 'k', '\0', '\0',
3 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question arises, is it possible to create your own header fil
4 min read
Write your own memcpy() and memmove()
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. void * memcpy(void * destination, const void * source, size_t num);The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of t
4 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
How to Write Our Own STL Container?
The Standard Template Library (STL) in C++ provides us with various data structures and algorithms. We have STL containers like vector, list, map, and set that we commonly use to store and manipulate data efficiently. However, there are situations where the existing STL containers may not meet our specific requirements, so we may want to create our
7 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we define any type of constructor manually in the class. ExplanationThe default constructor is used to create an object's instance without any arguments. In C++, the compiler implicitly creates a default constructor for every class which doesn't have user defined constructor so that at
2 min read
Is it fine to write void main() or main() in C/C++?
In C/C++ the default return type of the main function is int, i.e. main() will return an integer value by default. The return value of the main tells the status of the execution of the program. The main() function returns 0 after the successful execution of the program otherwise it returns a non-zero value. Using void main in C/C++ is considered no
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg