Incompatibilities between C and C++ codes
Last Updated :
29 Jun, 2017
The C/C++ incompatibilities that cause most real problems are not subtle. Most are easily caught by compilers.
This section gives examples of C code that is not C++ :
1) In C, functions can be defined using a syntax that optionally specifies argument types after the list of arguments:
#include<stdio.h>
void fun(a, b) int a; int b;
{
printf ( "%d %d" , a, b);
}
int main()
{
fun(8, 9);
return 0;
}
|
Output:
8 9
Error in C++ :- a and b was not declared in this scope
2) In C and in pre-standard versions of C++, the type specifier defaults to int.
#include<stdio.h>
int main()
{
const a = 7;
printf ( "%d" , a);
return 0;
}
|
Output:
7
Error in C++ :- a does not name a type
3) In C, a global data object may be declared several times without using the extern specifier. As long as at most one such declaration provides an initializer, the object is considered defined only once.
#include<stdio.h>
int a; int a;
int main()
{
return 0;
}
|
Error in C++ :- Redefinition of int a
4) In C, a void* may be used as the right-hand operand of an assignment to or initialization of a variable of any pointer type.
#include<stdio.h>
#include<malloc.h>
void f( int n)
{
int * p = malloc (n* sizeof ( int ));
}
int main()
{
f(7);
return 0;
}
|
Error in C++ :- Invalid conversion of void* to int*
5) In C, an array can be initialized by an initializer that has more elements than the array requires.
#include<stdio.h>
int main()
{
char array[5] = "Geeks" ;
printf ( "%s" , array);
return 0;
}
|
Output:
Geeks
Error in C++ :- Initializer-string for array of chars is too long
6) In C, a function declared without specifying any argument types can take any number of arguments of any type at all. Click here to know more about this.
#include<stdio.h>
void fun() { }
int main( void )
{
fun(10, "GfG" , "GQ" );
return 0;
}
|
Error in C++ :- Too many arguments to function 'void fun()'
Related Articles:
If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.
Share your thoughts in the comments
Please Login to comment...