我正在尋找一些C++代碼,並且被if(ptr && *ptr)
弄糊塗了,在這種情況下它有什麼作用?爲什麼在C++中if語句中使用指針及其取消引用
// Process the data here. We just break the data into separate pieces and
// display it for the sake of simplicity.
char * a_pszBreak = NULL;
char * a_pszDataItem = (char*)s_aucDataBuffer;
do
{
// The poll data is terminated by either a Carriage Return alone, or a
// Carriage Return/Line Feed pair.
a_pszBreak = strpbrk(a_pszDataItem, "\n\r");
if (a_pszBreak && *a_pszBreak)
{
*a_pszBreak = 0;
a_pszBreak++;
LogPollData((const char *)a_pszDataItem);
}
a_pszDataItem = a_pszBreak;
} while (a_pszBreak && *a_pszBreak);
這是爲了防止不正確地解引用一個空指針的方法的字符串。 &&短路,所以如果'ptr'爲NULL''ptr'永遠不會嘗試(如果有的話,它會發生段錯誤)。 –
你確實知道你可以解引用(使用解引用運算符'*')一個'NULL'指針嗎?你知道邏輯運算符'&&'和'||'做[short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation)嗎?你知道'NULL'指針被認爲是「false」?你知道字符串以零結尾嗎?而且任何非零的東西都被認爲是「真的」?如果你知道所有這五件事情,那麼把這些知識放在一起,再多思考一下。 –
不要在C++中使用指針。這不再是1995年。您正在閱讀的代碼非常陳舊。 –