Search code examples
cgccc99gnu99

Is 'redefining' variables in statement expressions safe?


My question is regarding statement expressions, which are added as an extension in GNU C. Consider the following code:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    int i = 0;
    printf("%d\n", i);

    {int i = 1;printf("%d\n", i);}

    printf("%d\n", i);
    return EXIT_SUCCESS;
}

Compiling (gcc -Wall -std=gnu99 lala.c -o lala) and running will yield:

0
1
0

This practice (usage of the extension) is fairly commonplace, notably in container_of in the Linux kernel:

#define container_of(ptr, type, member) ({ \
                const typeof( ((type *)0)->member ) *__mptr = (ptr); 
                (type *)( (char *)__mptr - offsetof(type,member) );})

Similar to this case, I want to define a macro which declares a local variable and does something with it. However, I want to do so without polluting the variable names available at the current scope and avoid possible redefinitions. I was not able to find in the documentation information on how exactly the scoping happens in cases of redefinitions.

In the case above, no warning is issued from the compiler regarding a redefinition. My question is whether I can rely on the fact that the variable scoped inside the statement expression will not affect the variable of the same name in the outer scope?


Solution

  • Sure this is safe, this is what scopes are made for.

    (And as dreamlax indicates in his comment, identifiers with two underscores are reserved for the implementation (compiler, library, hosting environement...) so you shouldn't use them.)