What happens if I define a 0-size array in C/C++?

后端 未结 7 1516
轻奢々
轻奢々 2020-11-22 03:47

Just curious, what actually happens if I define a zero-length array int array[0]; in code? GCC doesn\'t complain at all.

Sample Program

7条回答
  •  悲哀的现实
    2020-11-22 04:07

    It's totally illegal, and always has been, but a lot of compilers neglect to signal the error. I'm not sure why you want to do this. The one use I know of is to trigger a compile time error from a boolean:

    char someCondition[ condition ];
    

    If condition is a false, then I get a compile time error. Because compilers do allow this, however, I've taken to using:

    char someCondition[ 2 * condition - 1 ];
    

    This gives a size of either 1 or -1, and I've never found a compiler which would accept a size of -1.

提交回复
热议问题