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


Here, we will write some c programs that won’t compile in c++. Though c++ is considered as a successor of c that has all its features and has compatibility with c code there are some programs that won’t compiler or given a compilation error when compiled with c++ compiler.

A list of some of the C programs that won’t compile in c++ are −

  • Call to a function before declaration − In c++, function call before declaration gives compilation error. But this works fine in c.

Example

 Live Demo

#include <stdio.h>
int main(){
   printHello();
   return 0;
}
void printHello(){
   printf("TutorialsPoint");
}

Output

TutorialsPoint
  • Using typecasted pointers − if we declare a pointer in c as void and then use this pointer to point other data variables. This can be done in c by the compiler itself but in c++, these pointers need to be typecasted.

Example

 Live Demo

#include <stdio.h>
int main(){
   void *ptr;
   int *ptr2 = ptr;
   return 0;
}
  • Declaring constant values without initialising − in c, you can declare constant values without providing any value to it but this returns an error when done in c++.

Example

 Live Demo

#include <stdio.h>
int main(){
   const int x;
   printf("%d", x);
   return 0;
}

Output

0
  • Using normal pointer with const variable − in c++ this is not allowed while c allows the use of const variable with a normal pointer.

Example

 Live Demo

#include <stdio.h>
int main(void){
   int const x = 3424;
   int *cptr = &x;
   printf("value of pointer : %d\n", *cptr);
   return 0;
}

Output

 Value of pointer: 3424
  • Using specific keywords as variable names − In c programming language use of certain keywords as variable names is valid i.e. would compile in c but won’t compile in c++.

Example

 Live Demo

#include <stdio.h>
int main(void){
   int class = 5;
   printf("%d", class);
}

Output

5

These are those keywords that are included in c++, some more are new, delete, explicit, etc.

Updated on: 17-Jul-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements