Questionable C/C++ statement

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux