我最近對代碼進行了一些調整,其中我必須更改函數中的形式參數。原來,該參數是類似以下內容(注意,結構早前typedef定義):聲明const的指針或const指針作爲形式參數
static MySpecialStructure my_special_structure;
static unsigned char char_being_passed; // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure; // Passed to function elsewhere.
int myFunction (MySpecialStructure * p_structure, unsigned char useful_char)
{
...
}
做出更改,因爲我可以定義並初始化my_special_structure之前編譯時和myFunction的從未改變它的價值。這導致了以下變化:
static const MySpecialStructure my_special_structure;
static unsigned char char_being_passed; // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure; // Passed to function elsewhere.
int myFunction (const MySpecialStructure * p_structure, unsigned char useful_char)
{
...
}
我還注意到,當我跑絨我的程序,有幾個信息818的引用許多不同的功能。信息指出「指針參數'x'(第253行)可以被聲明爲指向const」「。
現在,我有兩個問題關於上述。首先,關於上面的代碼,由於MySpecialStructure中的指針和變量都沒有在函數內改變,所以將指針聲明爲常量是否有益呢?例如 -
int myFunction (const MySpecialStructure * const p_structure, unsigned char useful_char)
我的第二個問題是關於Lint信息。如果函數不改變它的值,那麼將指針指定爲常量形式參數是否有任何優點或缺點...即使傳遞給函數的內容從未被聲明爲常量?例如 -
static unsigned char my_char;
static unsigned char * p_my_char;
p_my_char = &my_char;
int myFunction (const unsigned char * p_char)
{
...
}
感謝您的幫助!
編輯澄清 -
什麼是聲明指針const
或const
指針const
的優勢 - 作爲一個正式的參數?我知道我可以做到這一點,但我爲什麼要...特別是在傳遞指針和它指向的數據沒有聲明爲常量的情況下?
我的意思是一個指向'const'的指針,謝謝......當我試圖澄清只是爲了增加更多混淆時,我討厭它。 – 2012-02-23 19:09:47