在 C/C 中檢查 NULL 指標的最佳方法是什麼?
在最近的程式碼審查中,貢獻者斷言所有NULL指標檢查應該透過與NULL 的明確比較來執行:
<code class="cpp">int * some_ptr; // ... if (some_ptr == NULL) { // Handle null-pointer error } else { // Proceed }</code>
這種方法遭到了另一位審閱者的反對,他認為在if 語句中使用指標變數的傳統方法也是有效且簡潔的檢查NULL 的方法:
<code class="cpp">int * some_ptr; // ... if (some_ptr) { // Proceed } else { // Handle null-pointer error }</code>
。您喜歡哪一種方法?為什麼?
根據首選答案,後一種方法較可取,原因如下:
總之,在 C/C 中檢查 NULL 指標時,首選方法是使用慣用的 if (ptr) 或 if (!ptr) 語法。這種方法清晰、簡潔,並且與 C 類相容。
以上是在 C/C 中應該使用 `if (ptr == NULL)` 還是 `if (ptr)` 進行空指標檢查?的詳細內容。更多資訊請關注PHP中文網其他相關文章!