I wish to write a program that successfully compiles with a C compiler as well as a C++ compiler. How would I achieve this?
Ans: Though every C program is a successful C++ program as well, the reverse is not true. We may want that if the program is compiled using a C++ compiler we should be able to use C++ features in it. However, we must also be able to successfully compile the same program using a C compiler. We can achieve this by using a conditional compilation directive using a constant called __cplusplus. This constant is defined by Borland C++. Every C++ compiler provides such a constant. Following program shows how to use __cplusplus.
#ifdef __cplusplus
#include <iostream.h>
class emp
{
private :
int id ;
float sal ;
char *n ;
public :
emp ( int i, float s, char *nn )
{
id = i ;
sal = s ;
n = nn ;
}
void p( )
{
cout << endl << id << sal << n ;
}
} ;
#else
#include <stdio.h>
struct emp
{
int id ;
float sal ;
char *n ;
} ;
void p ( struct emp t )
{
printf ( “%d %f %s”, t.id, t.sal, t.n ) ;
}
#endif
main( )
{
#ifdef __cplusplus
emp e ( 6, 2300.50, “Sameer” ) ;
e.p( ) ;
#else
struct emp e = { 6, 2300.50, “Sameer” } ;
p ( e ) ;
#endif
}
This program can run on both C and C++ compilers. To check this, first save the program in ‘.cpp’ file and then in ‘.c’ file. It should run in both the cases.