Why are compound literals in C modifiable

后端 未结 2 1351
暗喜
暗喜 2020-12-01 15:05

One does usually associate \'unmodifiable\' with the term literal

char* str = \"Hello World!\";
*str = \'B\';  // Bus Error!

However when u

2条回答
  •  温柔的废话
    2020-12-01 15:27

    The compound literal syntax is a short hand expression equivalent to a local declaration with an initializer followed by a reference to the unnamed object thus declared:

    char *str = (char[]){ "Hello World" };
    

    is equivalent to:

    char __unnamed__[] = { "Hello world" };
    char *str = __unnamed__;
    

    The __unnamed__ has automatic storage and is defined as modifiable, it can be modified via the pointer str initialized to point to it.

    In the case of char *str = "Hello World!"; the object pointed to by str is not supposed to be modified. In fact attempting to modify it has undefined behavior.

    The C Standard could have defined such string literals as having type const char[] instead of char[], but this would generate many warnings and errors in legacy code.

    Yet it is advisable to pass a flag to the compiler to make such string literals implicitly const and make the whole project const correct, ie: defining all pointer arguments that are not used to modify their object as const. For gcc and clang, the command line option is -Wwrite-strings. I also strongly advise to enable many more warnings and make them fatal with -Wall -W -Werror.

提交回复
热议问题