Home  >  Article  >  Backend Development  >  Incompatibility between C and C++

Incompatibility between C and C++

PHPz
PHPzforward
2023-08-28 18:33:061083browse

Incompatibility between C and C++

Here we will see some incompatibilities between C and C. Some C code that can be compiled using a C compiler cannot be compiled in a C compiler. and will return an error.

  • We can define functions using a syntax that optionally specifies parameter types after the parameter 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 language or some older versions of C, the default variables Type is integer. But in new versions of C, an error occurs.

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 language, global data objects can be declared multiple times without Use the extern keyword. The C compiler will treat this as one declaration among many.

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 language, we can use void pointer as assignment operator The right operand, or used to initialize any variable of 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 language, if the parameter type is not specified, we can pass Multiple parameters.

Example

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

Output

Inside my_function

Output

Error in C++ :- Too many arguments to function &#39;void my_function()&#39;

The above is the detailed content of Incompatibility between C and C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete