LoginSignup
5
5

More than 5 years have passed since last update.

const の指定の仕方とコンパイルエラーについて

Posted at

レビューで指摘したので、ついでに書いておくことにする。
const を正しく指定しましょうという話。

main.c
char *char1 = "ab";
const char *char2 = "bc";
char *const char3 = "cd";
const char * const char4 = "de";

int main() {
    char1[0] = 'x';
    char1 = "new";

    char2[0] = 'x';
    char2 = "new";

    char3[0] = 'x';
    char3 = "new";

    char4[0] = 'x';    
    char4 = "new";

    return 0;
}

ビルド結果

main.c:12:14: error: read-only variable is not assignable
char2[0] = 'x';
~~~~~~~~ ^
main.c:16:11: error: read-only variable is not assignable
char3 = "new";
~~~~~ ^
main.c:18:14: error: read-only variable is not assignable
char4[0] = 'x';    
~~~~~~~~ ^
main.c:19:11: error: read-only variable is not assignable
char4 = "new";
~~~~~ ^
4 errors generated. 
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5