在常讨论问题的qq group中看到大家对一个问题争论不一,本着学习的态度,编写demo,复习和学习相关知识,如有错误欢迎指正。

const例子一:
#include <stdio.h>

int main()
{
       /*这里加*表示数组parr内容不能修改即使用下面注释的语句赋值是非法的*/
    char * const parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    //parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}
const例子二:
#include <stdio.h>

int main()
{
       /*这里加*表示数组parr元素类型是const char *,使用gcc编译没问题,使用g++有告警,见下例*/
    const char * parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}
const例子三:
#include <iostream>

int main()
{
      /*这里加*表示数组parr元素类型是const char *,不加const使用g++有告警*/
    const char * parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}

告警内容如下:

root@52coder:~/workspace# g++ -g  -Wall -o  const const.cpp
const.cpp: In function ‘int main()’:
const.cpp:6:33: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
     char * parr[] = {"abc","def"};
                                 ^
const.cpp:6:33: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
const.cpp:7:17: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
     char *ptr = "Helloworld";
                 ^~~~~~~~~~~~
root@52coder:~/workspace#