Inconsistent gcc diagnostic for string initialization

后端 未结 3 929
小鲜肉
小鲜肉 2020-12-01 22:29

I\'m using gcc 4.9.1/Mingw and compiling the code with:

gcc test.c -otest.exe -std=c11 -pedantic-errors -Wall -Wextra

This code

3条回答
  •  甜味超标
    2020-12-01 23:08

    It's a weird quirk in the C Standard. Back in the day, people occasionally used fixed-length, non-null-terminated strings. (One example was the 14-character filenames in V7 Unix.) So to let those old programs to continue to compile, it's legal to initialize an explicitly-sized char array with a string constant that ends up scraping off the '\0', as you've just observed.

    I agree it's surprising that the {'h','e','l','l','o','\0'} initializer warned while the "hello" one did not. But these are two very different forms, and it turns out that the rules for them are different. When you give your array a size and you use the {} form, there must be room for all your initializers, period. But when you give a size and use the "" form, there's a special exception for that case and that case only.

    (It's also not legal in C++ for either form.)

提交回复
热议问题