Why ISO C prohibits casting non-scalar to the same type

struct Foo {
    int dummy;
} bar;

int main(void)
{
    /* This statement causes GCC to produce the warning:
     * ISO C forbids casting nonscalar to the same type */
    (volatile struct Foo)bar;

    /* The warning may be silenced like so.
     * Is this form superior or just trickier? Why? */
    *(volatile struct Foo *)&bar;

    return 0;
}

      

What evil is the compiler / standard trying to defend against?

Background: The real code in question uses a circular buffer / queue shared between the ISR and the background. The background code is constantly checking the queue. I was trying to avoid pessimizing the access to the queue by not allowing the compiler to optimize the polling of the queue so that the code would go into a compressed loop label: goto label;

when the queue is empty.

+3


source to share


2 answers


The warning message is a little misleading. ISO C doesn't just prohibit casting a non-scalar to the same type; it prohibits throwing non-scalar to or from any type. Both the operand of the cast operator and the type specified in the product itself must be of a scalar type (either arithmetic or pointer).



There is an exception here, but it does not apply here. If the Target Type is invalid, the operand can be of any type.

+5


source


the posted definition of struct foo also declares an instance of a structure named "bar".

Then, inside the code, a second instance of the structure is declared, again named "bar".

the second "bar" shades the first instance.

which alone will cause the compiler to raise the warning.



here's the correct usage (there is still a shading issue)

struct Foo {
    int dummy;
} bar;

int main(void)
{
    /* This statement causes GCC to produce the warning:
     * ISO C forbids casting nonscalar to the same type */
    volatile struct Foo bar;

    /* The warning may be silenced like so.
     * Is this form superior or just trickier? Why? */
    //*(volatile struct Foo *)&bar;

    return 0;
}

      

Note that you are not trying to redefine the structure Foo as volatile, instead of declaring the local variable 'bar' as volatile

0


source







All Articles