専攻科実験のサンプルコードで、警告がでたことについて質問があったので説明。
(( サンプルコード sample.cxx ))
#include <stdio.h>
void foo( char* s ) {
  printf( "%s¥n" , s ) ;
}
int main() {
  foo( "ABC" ) ;
  return 0 ;
}
(( コンパイル時の警告 ))
$ g++ sample.cxx
test.cxx:6:6: warning: conversion from string literal
      to 'char *' is deprecated
      [-Wc++11-compat-deprecated-writable-strings]
  foo( "abcde" ) ;
       ^
1 warning generated.
警告を抑止する “-Wno-…” のオプションをつけて “g++ -Wno-c++11-compat-deprecated-writable-strings sample.cxx” でコンパイルすることもできるけど、ここは変数の型を厳格にするのが鉄則。
この例では、引数の “ABC” が書き換えのできない定数なので、const キーワードを付ければよい。ただし、宣言時の const の付け場所によって、意味が違うので注意が必要。
void foo( char const* s ) { // const char* s も同じ意味 *s = 'A' ; // NG ポインタの先を書き換えできない s++ ; // OK ポインタを動かすことはできる } void foo( char *const s ) { *s = 'A' ; // OK ポインタの先は書き込める s++ ; // NG ポインタは動かせない } void foo( char const*const s ) { *s = 'A' ; // NG ポインタの先を書き換えできない s++ ; // NG ポインタは動かせない }
const を書く場所は?
int const x = 123 , y = 234 ; の場合、yは定数だろうか?
(( おまけ ))
#include <stdio.h>
int main() {
  int const x = 123 , y = 234 ; // x は定数だけど yは定数?
  x++ ; // 予想通りエラー
  y++ ; // yも定数なのでエラー
  int const s = 345 , const t = 456 ; // sもtも明らかに定数っぽい
  //                  ^ここで文法エラー
  // おまけのおまけ
  char* s , t ;   // s は文字へのポインタ、t は文字
  char  *s , *t ; // s は文字へのポインタ、t も文字へのポインタ
  return 0 ;
}