I took a test and the test said this following code is not compilable in either C or C++. Not sure which one. Why is this so? Seems perfectly compilable to me in both worlds.
1 2 3 4 5 6 7
void foo(int n) {
printf("%d", n);
int i;
for (i=0; i<n; i++) {
printf("%d", i);
}
}
Check all functions that are compilable by both c and c++ compilers.
void foo(int n) {
printf("%d", n);
int i;
for (i=0; i<n; i++) {
printf("%d", i);
}
}
void foo() {
for (int i=0; i<10; i++) {
printf("%d", i);
}
}
void foo() {
int i;
for (i=0; i<10; i++) {
// printf("%d", i);
}
}
void foo() {
int i;
for (i=0; i<10; i++) {
printf("%d", i);
}
}
Why is the first code not compilable in either c or c++? It should be compilable right?
In C89 (ANSI C), all variables have to be declared at the top of the function, so line 4 is definitely an issue there.
Line 11 is also not valid C89 to my knowledge. The int i would have to be declared on its own line at the start of the function.
In C99, these restrictions were lifted. Just saying "C" is kind of ambiguous because there's a lot of legacy code out there.
If you know you're at least using C99, then you don't need to worry about this. Personally I don't see the benefit to keeping something as ANSI C unless for legacy maintenance reasons.
Edit: Oh, and for line 19: The trick there is that // comments weren't standard until C99.
So you have to use /* */ in ANSI C.