開発環境 |
Microsoft Visual C++ 2010 Express (SP1) |
実行環境 |
Microsoft Windows XP Home Edition (SP3) |
プロジェクトの種類 |
Win32 コンソール アプリケーション |
プロジェクト名 |
const |
アプリケーションの種類 |
コンソール アプリケーション |
追加のオプション |
空のプロジェクト |
const.c
#include <stdio.h>
// 受け取った文字列の内容を変更する可能性がある
void sub1(char *p)
{
// *p = 'H'; // コンパイルは通るが、文字列定数への代入で実行時にエラー
while (*p) {
putchar(*p++);
}
}
// 受け取った文字列の内容を変更しないことを保証する
void sub2(const char *p)
{
// *p = 'H'; // error C2166: 左辺値は const オブジェクトに指定されています。
while (*p) {
putchar(*p++);
}
}
// ほとんど見かけないが、受け取ったポインタ変数の値を変えたくない場合に使う
void sub3(const char * const p)
{
int i = 0;
while (p[i]) {
putchar(p[i++]);
}
}
int main()
{
sub1("hello, world\n");
sub2("hello, world\n");
sub3("hello, world\n");
return 0;
}
最終更新:2012年09月10日 22:19