This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Questionable C/C++ statement


I recently came across some C++ code that I thought is illegal, but G++
compiles (actually, the G++ provided with VxWorks).  I was wondering if this
is legal Ansi C++ or if it is a compiler bug (since it compiles and code
appears to run).

As a test, I tried using GCC version 3.2 and it produces the same behavior.
I am not up on the assembler so can't quite see if it figures out the right
thing.

A sample program that contains questionable code (foo) and similar code
without the issue (bar)

#include <stdio.h>

volatile int mx;

void foo(void)
{
    unsigned char buf[mx];
    register int i;
    for (i = mx; i >= 0; i--)
        fprintf(stderr, "0x%02.2X ", buf[i]);
}

void bar(void)
{
    unsigned char buf[5];
    register int i;
    for (i = mx; i >= 0; i--)
        fprintf(stderr, "0x%02.2X ", buf[i]);
}

int main(int ac, char **av)
{
    int i;
    for (i = 0; i < 5; i++)
    {
        mx = 5 * i;
        foo();
    }
    for (i = 0; i < 5; i++)
    {
        mx = 5;
        bar();
    }
    return 0;
}

I expect that buf is put on the stack, and didn't think that a variable can
be defined with a dynamic size (buf[mx]).  My recollection is that the stack
offsets are calculated at compile time, so this would be an error, since the
value is not known at compile time.

Is this syntactically legal or is this a compiler bug?  If someone is up to
it, does the assembler for foo() make sense?

Note that the disassembly for the two functions is significantly different.

	Dave


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]