Question

I've tried to read the relavent sections of standard (secs 6.5 and 6.8 of c99), but this lead me to be more confused and without a clear answer. This is the code in question:

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

int t;
#define block {\
    int temp = 1; \
    t = time(NULL); \
    if (t == (time_t) -1 && temp) puts("turbulance ahead!");\
}

int main(){
    if (((block), t%2)) {
        puts("nice 'n even");
    }
    else {
        puts("odd..");
    }
    return 0;
}

Is the code valid c99/c1x? It compiles on clang and gcc without producing any errors, even when -Wall and -Wextra are set.

Was it helpful?

Solution

No. It's not valid under Standard C (C99/C11).

It's valid in GNU C, an extension as called statement expressions.

OTHER TIPS

if (((block), t%2))

This evaluates to a statement expression followed by a comma operator. The return value of a block expression is the value of the last statement in the block. Comma operator evaluates from left to right and its value is equal to the last expression. If you try the -E option in gcc, you will get the preprocessed code, which looks like this:

if ((({ int temp = 1; t = time(((void *)0)); if (t == (time_t) -1 && temp) puts("turbulance ahead!");}), t%2)) 

So the condition in if statement is solely determined by the value of t%2(as per comma operator).

Is the code valid c99/c1x?

No. C99 generates warning for statement expressions.

It compiles on clang and gcc

No it doesn't. Compile it as the C language, not as the "GNU goo" language.

gcc file.c -std=c99 -pedantic-errors -Wall -Wextra
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top