Declaring an array of negative length

前端 未结 3 1959
谎友^
谎友^ 2020-11-30 14:38

What happens in C when you create an array of negative length?

For instance:

int n = -35;

int testArray[n];

for(int i = 0; i < 10; i++)
    test         


        
相关标签:
3条回答
  • 2020-11-30 15:19

    Visual studio erro message for compilation, you can use -1 to say an empty array. It expects int and you are passing int, so no compiler error.

    0 讨论(0)
  • It's undefined behaviour, because it breaks a "shall" constraint:

    C99 §6.7.5.2:

    If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.

    0 讨论(0)
  • 2020-11-30 15:29

    Undefined behavior, I believe, though don't quote me on that.

    This gives the error error: size of array 'testArray' is negative in gcc:

    int testArray[-35];
    

    though, as you've seen:

    int n = -35;
    int testArray[n];
    

    does not give an error even with both -Wall and -W.

    However, if you use -pedantic flag, gcc will warn that ISO C90 forbids variable length array.

    0 讨论(0)
提交回复
热议问题