this question was asked to my friend in an interview. "can you write any program that will compile in C but not in C++". is there any such program?
Depending on which version of C, I guess I would've chickened out and put
int main() {
/* This is invalid in pre-C99! */
}
:)
#include <stdlib.h>
int main()
{
char* p = malloc(10);
return 0;
}
int main(int new, char **class) {}
Compiles in C, but not in C++ because in C++ new
and class
are keywords and can't be used as identifiers.
For C89, you also need return 0;
in the body of the function. Using C99 was a bit of a cheat anyway, because C99 has loads of features which aren't in C++. Here I use complex types, stdint, restrict
and VLAs:
#include <complex.h>
#include <stdint.h>
typedef double _Complex dc;
int funny_average(dc * restrict a, dc * restrict b, uint16_t n) {
dc array[n+2];
memset(array, 0, sizeof array);
array[0] = *a;
array[1] = *b;
return normal_average(array, n + 2);
}
You get the idea. Some, all, or none of these might be supported as extensions by any given C++ implementation, but they aren't standard (Actually, uint16_t is optional in C99, so strictly speaking this code might not compile as C either).
int main()
{
int x[-2 + sizeof('a')];
return 0;
}
Ooh, ooh!
#ifdef __cplusplus
FAIL TO COMPILE HORRIFICALLY!
#else
int main() { return 0; }
#endif
Why complicate things?
int main() {
int class = 7;
}
This is a shot:
main(int argc,char**argv){ char *p=malloc(0); return 0; }
Best regards, Tom.
int main(int argc, char * * argv)
{
int status;
while (argc > 0)
{
status = main(argc - 1, argv);
}
return EXIT_SUCCESS;
}
In C, the main
function can be executed from inside the program.
(Critics: If this is not true, note the version of C where the specification changed.)