Incompatibilities between C and C++


Here we will see some incompatibilities between C and C++. Some C codes that can be compiled using C compiler, but does not compile in C++ compiler. And also returns error.

  • We can define function using a syntax, that optionally specify the argument types after the argument list.

Example

#include<stdio.h>
void my_function(x, y)int x;int y; { // Not valid in C++
   printf("x = %d, y = %d", x, y);
}
int main() {
   my_function(10, 20);
}

Output

x = 10, y = 20

Output

Error in C++ :- x and y was not declared in this scope
  • In C, or some older version of C++, the default variable type is integer. But in newer C++, it will generate an error.

Example

#include<stdio.h>
main() {
   const x = 10;
   const y = 20;
   printf("x = %d, y = %d", x, y);
}

Output

x = 10, y = 20

Output

Error in C++ :- x does not name a type
y does not name a type
  • In C, the global data objects may be declared many times without using the extern keyword. C compiler considers it once for multiple declarations.

Example

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

Output

x = 10

Output

Error in C++ :- Redefinition of int x
  • In C, we can use void pointer as the right hand operator of an assignment to or initialize the variable of any pointer type.

Example

#include<stdio.h>
#include<malloc.h>
void my_function(int n) {
   int* ptr = malloc(n* sizeof(int)); //implicitly convert void* to int*
   printf("Array created. Size: %d", n);
}
main() {
   my_function(10);
}

Output

Array created. Size: 10

Output

Error in C++ :- Invalid conversion of void* to int*
  • In C, if the argument type is not specified, we can pass multiple arguments.

Example

#include<stdio.h>
void my_function() {
   printf("Inside my_function");
}
main() {
   my_function(10, "Hello", 2.568, 'a');
}

Output

Inside my_function

Output

Error in C++ :- Too many arguments to function 'void my_function()'

Updated on: 30-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements