Question

When trying to compile the following snippet of code:

#include <stdio.h>
#include <time.h>

void change_a(int * a) {
    *a = 1;
    return;
}

void main(void) {
    int a = 0;
    change_a(&a);
    if (a) {
        time_t start = time(NULL);
    }
/* do something that never mentions a */

    if (a) {
        time_t end = time(NULL);
       printf("Time spent = %ld\n", (int) end - start);
    }
}

GCC states that the start variable is undefined in the printf line:

$ gcc --version
gcc (Debian 4.8.2-1) 4.8.2
[SNIP]
$ gcc -o test.bin test.c 
test.c: In function ‘main’:
test.c:24:44: error: ‘start’ undeclared (first use in this function)
   printf("Time spent = %ld\n", (int) end - start);

On the other hand, it compiles and works OK when changing the main function to:

void main(void) {
    int a = 0;
    time_t start = 0;

    change_a(&a);
    if (a) {
        start = time(NULL);
    }
    ...

Question 1

Am I doing something wrong or is the compiler doing something funny I don't know about?

I think it may be the compiler being too smart and optimizing that piece of code out or having a failure in its heuristics or something. But every other time I've "found compiler bugs" it was always me missing some very obvious error.

So I'd rather intelligent people check this before I accuse other smart people of not being so smart. Specially when the issue also happens without optimization:

$ gcc -O0 -o test.bin test.c 
test.c: In function ‘main’:
test.c:24:44: error: ‘start’ undeclared (first use in this function)
   printf("Time spent = %ld\n", (int) end - start);
                                            ^
test.c:24:44: note: each undeclared identifier is reported only once for each function it appears in

Question 2

I'd also like to know if there is a better way to avoid the compiler error (if not the workaround in the last code snippet). This is kind of obvious if it is my code that is wrong (as the response would include the "correct" code), but I would also like to know how to avoid the error while someone fixes the (alleged) bug in GCC.

Was it helpful?

Solution

In your first example, the start variable is declared inside the scope of the if statement. The variable therefore goes out of scope at the end of the code block (the closing curly brace }). This is definitely not a compiler bug.

Your "workaround" is the correct solution.

See here for a more thorough description of how variable scope works in C/C++ (and many other languages which use C-style scoping).

OTHER TIPS

maybe "start" scope is in
if (a) { time_t start = time(NULL); }
start is cannot refernce out of if block

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top