Compilable or not compilable

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);
  }
}
You need a main function to mark the beginning of program.
How much pedantry do you want?

Assuming it's placed in an otherwise compilable module with the correct header files, then the code will not compile in C89.

But it will compile in C99 and C++.

Mm I know. But my test they have a few options:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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?
Last edited on
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.
Last edited on
> Why is the first code not compilable in either c or c++?

Need to include the header <stdio.h>
But JLBorges, do you really think that's what the instructor is going for?

I really don't understand why the first code wouldn't be compilable in C++.

Anyway, these kinds of questions are quite silly and don't reflect actual ability, in my opinion.
Last edited on
Don't really know what the career teacher is implying;
but there is no other reason why it would not be compilable.
Topic archived. No new replies allowed.