This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

CCS - cannot declare array of size stored in variable known on compile-time

Expert 1140 points

Hi,

Just switched from gcc to CCSv6 and saw this surprising fact.

#include <msp430.h> 

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;

    int count = 30;

    char array[count];

    P1DIR |= BIT0;
    P1OUT |= BIT0;

	return 0;
}

Program execution stops on "char array[count]" even though count is known at compile-time to be equal to 30. GCC works ok, while for CCS it doesn't. It doesn't work for const int either. Why is that?

  • The value of the variable count may vary at run-time. The compiler only knows its initial value. It cannot predict how it varies at run-time. In my opinion, the compiler should have complained at compilation-time and should not have let it execute (run) at all.

  • old_cow_yellow said:
    The value of the variable count may vary at run-time. The compiler only knows its initial value. It cannot predict how it varies at run-time. In my opinion, the compiler should have complained at compilation-time and should not have let it execute (run) at all.

    Well, agree but in this case it should work for const int count = 30; and it doesn't.

  • Hmm! interesting, Just realised now. looking for this a lot of reading to be done.

  • tml said:
    Well, agree but in this case it should work for const int count = 30; and it doesn't.

    For the code (and the compiler), count is still a reference of a memory content, and not a constant value (like a #define would).

    Variable-sized arrays aren't really supported in the original C language. Even tough newer standard more or less allow it.
    Anyway, a local array is allocated at run-time on stack, blowing the stack size up instantly. Neither compiler nor linker can do any stack size check. But maybe the debugger notices that the stack overflows as soon as the code wants to allocate the array during code execution.

    As a rule of thumb, main shouldn't declare any local vars. Since main never exits during program execution, they can as well be declared as static, so the linker can consider their size at link time.

    And allocating huge arrays or even arrays of dynamic size at runtime as local vars in a function, is a source for all kinds of problems. Especially if the system you use doesn't have unlimited ram or stack segments with memory protection or such things.

**Attention** This is a public forum