【编程好习惯】将常量放在“==”之前
生活随笔
收集整理的這篇文章主要介紹了
【编程好习惯】将常量放在“==”之前
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于圖1中的程序其中存在一個問題,那就是38行if語句中的判斷條件,這一程序的結果是只有else語句中的程序會被執行。其中的錯誤在于,if語句中本應是“==”,但卻被誤寫成了“=”,因而_p_ref中的prev_被斌值成了零,接著if語句判斷其是否為true,由于零被當作是false所以永遠只有else語句中的程序會被執行。
dll.c00036: void dll_insert_before (dll_t *_p_dll, dll_node_t *_p_ref,
dll_node_t *_p_inserted)
00037: {
00038: ? ? if (_p_ref->prev_ = 0) {
00039: ? ? ? ? _p_dll->head_ = _p_inserted;
00040: ? ? ? ? _p_ref->prev_ = _p_inserted;
00041: ? ? ? ? _p_inserted->next_ = _p_ref;
00042: ? ? ? ? _p_inserted->prev_ = 0;
00043: ? ? }
00044: ? ? else {
00045: ? ? ? ? _p_ref->prev_->next_ = _p_inserted;
00046: ? ? ? ? _p_inserted->prev_ = _p_ref->prev_;
00047: ? ? ? ? _p_inserted->next_ = _p_ref;
00048: ? ? ? ? _p_ref->prev_ = _p_inserted;
00049: ? ? }
00050: ? ? _p_dll->count_++;
00051: }圖1
類似這種錯誤有可能造成很大的問題,如何通過編程習慣去避免它呢?方法就是養成將常量放在“==”前面的習慣,如圖2中的38行所示。一旦“==”被誤寫成了“=”的話,由于常量零是不能用做左值的,因此,編譯器就能幫助發現這一失誤。顯然,當“==”兩邊的都是變量時,如果出現失誤,還是不能被發現。
dll.c00036: void dll_insert_before (dll_t *_p_dll, dll_node_t *_p_ref,
dll_node_t *_p_inserted)
00037: {
00038: ? ? if (0 == _p_ref->prev_) {
00039: ? ? ? ? _p_dll->head_ = _p_inserted;
00040: ? ? ? ? _p_ref->prev_ = _p_inserted;
00041: ? ? ? ? _p_inserted->next_ = _p_ref;
00042: ? ? ? ? _p_inserted->prev_ = 0;
00043: ? ? }
00044: ? ? else {
00045: ? ? ? ? _p_ref->prev_->next_ = _p_inserted;
00046: ? ? ? ? _p_inserted->prev_ = _p_ref->prev_;
00047: ? ? ? ? _p_inserted->next_ = _p_ref;
00048: ? ? ? ? _p_ref->prev_ = _p_inserted;
00049: ? ? }
00050: ? ? _p_dll->count_++;
00051: }圖2
如果做進一步思考的話,能否通過禁止在if的判斷條件語句使用“=”來徹底杜絕這類問題呢?當然,要做到這一步,這需要改變編譯器的行為,進一步還得更改C/C++語言的規范,這是個不小的動作。在某些情況下為了簡化程序書寫,會故意在if的判斷條件語句中使用“=”,但現在看來這種靈活性還是讓我們付出了代價。這就是C/C++語言!并不嚴謹的語法帶給了我們一定的靈活性,當然也給我們帶來了“意外”。這類靈活性我們真的需要嗎?除了if語句可以使用這一編程習慣,圖3示例了另一種情形。
example.c00054: ? ? stack_size = (0 == stack_size) ? STACK_DEFAULT : stack_size;圖3
轉載于:https://blog.51cto.com/yunli/264516
總結
以上是生活随笔為你收集整理的【编程好习惯】将常量放在“==”之前的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git 查看分支编码_12个常用的Git
- 下一篇: 面向对象编程(OOP)的基本思想