views:

155

answers:

1

There is a question in my programming languages textbook that is as follows:

Write a C function that includes the following sequence of statements:

x = 21; int x; x = 42;

Run the program and explain the results. Rewrite the same code in C++ and Java and compare the results.

I have written code, and played with it in all three languages but I can not even get it to compile. This includes declaring x above the three lines as well as in the calling function (as this question is obviously attempting to illustrate scoping issues)

I'd like to explain the results and do the comparisons on my own, as it is an assignment question but I was wondering if anyone had any insight as to how to get this code to compile?

Thanks

+4  A: 

Note the following requires C99:

int x;

void foo()
{
    x = 21;
    int x;
    x = 42;
}

Since this is homework, you'll need to provide your own explanation.

R Samuel Klatchko
That didn't want to compile for me. Likely because I didn't tell gcc to use C99. I'll give that a shot! Thanks.
Cody
@Cody - with gcc, you need to use the `-std=c99` option.
R Samuel Klatchko
Just compiled, and it worked fine. Explanation is now very obvious. Thanks!
Cody