#include <stdio.h>
main()
{
const int x = 10;
int *p;
p=&x;
*p=20;
printf("Value at p: %d \n",*p);
printf("Value at x: %d", x);
}
我得到的輸出是:
值在P:20
值x處:20
因此,恆定的變量的值被改變。這是使用指針的缺點之一嗎?
#include <stdio.h>
main()
{
const int x = 10;
int *p;
p=&x;
*p=20;
printf("Value at p: %d \n",*p);
printf("Value at x: %d", x);
}
我得到的輸出是:
值在P:20
值x處:20
因此,恆定的變量的值被改變。這是使用指針的缺點之一嗎?
請查看以下錯誤消息:
error: invalid conversion from ‘const int*’ to ‘int*’
const int
,int const
,const int *
,int const *
,請看到這個帖子:const int = int const?
這只是你如何使用它。
您使用的int*
指向一個const
INT。你應該:
error: invalid conversion from ‘const int*’ to ‘int*’
當你這樣做:
p = &x;
你可能需要更新您的編譯器,一個體面的編譯器應該告訴你這個錯誤,或者至少給你警告這一點。
但他沒有,因爲他使用了一個糟糕的編譯器,我想。 – Elazar 2013-05-06 01:35:08
@Elazar我想是的。或者可能是舊的版本編譯器 – taocp 2013-05-06 01:35:27
我使用gcc!我認爲gcc足夠好了! – user2350631 2013-05-06 01:38:15
那是因爲你使用了錯誤的方式和C語言編譯器讓你編譯這段代碼,而只給予警告
warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
而且有答案了,關於SO,如warning: assignment discards qualifiers from pointer target type
任何像樣的編譯器會告訴你,你被拋棄const屬性。
ç假定程序員永遠是對的,因此,它是你的選擇忽略編譯器的警告或不。像往常一樣,只要你知道你在做什麼,這不是一個缺點!
正如其他答案已經注意到,編寫一個程序,試圖修改const
這樣的限定變量導致程序有未定義的行爲。這意味着您的程序可以做任何事情 - 作爲這方面的一個例子,當我啓用的優化編譯程序,我看到這樣的輸出:
Value at p: 20
Value at x: 10
..和如果我的static
限定符添加到變量x
然後該程序在運行時崩潰。
C不會阻止你做這樣愚蠢的事。你得到來自編譯器警告,雖然:'const.c:9:警告:分配丟棄了指針目標type' – MatthewD 2013-05-06 01:33:24
'的#include「stdio.h中」'=>'#包括預選賽'注意 –
Elazar
2013-05-06 01:36:23
這取決於編譯器和優化已啓用,您可以在輸出中獲得「Value at x:10」。 – fbafelipe 2013-05-06 01:49:36