顯示具有 C++ 標籤的文章。 顯示所有文章
顯示具有 C++ 標籤的文章。 顯示所有文章

2021年3月12日 星期五

[Code Review] Check pointer not null

  • C 語言有非常強大的 pointer, 但也因此惡名昭彰
  • 兩個常用的情況是
    • Null pointer check
      •     	if (ptr != NULL) {
                	// do something ...
                } else {
                	// error handling
                }
            
      • 其中就相當多可以討論的地方
        • 要用 if (ptr) 還是 if (ptr != NULL) 還是 if (NULL != ptr)
        • 建議使用 if (ptr) 就好, 幾個理由如下
          • If (ptr ==) 類型的 check, 可能會少寫一個 =, 變成 assignment, 造成難追的 bug
          • NULL 的 implementation 未明確定義, 依不同 compiler 可能實作成 ((char *)0), ((void *) 0), 0, 0L 等
          • 相容於 smart pointer return bool 的 check
          • 降低不必要的 compare
        • Reference: Checking for null pointer in c
    • Memory leak
      • C++ 引入了 unique_ptr, shared_ptr, weak_ptr 等smart pointers
        • Auto release resource at desstructor

2020年11月4日 星期三

[Programming] void(p);

  • 今天 diff 兩個實作的程式碼, 某 function 的差異是多了一行
    void(p); 
    其中  p 是 function 參數
  • 這執行上完全沒有效果, 主要作用是避開有些 compiler 會有變數 unused 的 warning, 而 compiler 把 warning 也直接以 error 報錯時, 會 build error, 那可以用這方法避開.

2018年10月19日 星期五

[C++] header.h 與 cheader 的差異


  • 簡單解釋 
    • header.h 是 C++ 為了相容 C 保留的 header files
    • header.h 與 cheader 是 C 與 C++ 的對應, 但實際介面與實作上有些微差異
      • 如 cmath 中, abs 是以 overload 方式實作與提供介面, 但 math.h 則是 implement 多種 type 的 functions, e.g. fabs
    • 差異的地方是 cheader 將各 function 定義在 std的 namespace 下, 所以使用時要加 std:: 或是呼叫 using namespace std;
  • 實際使用
    • 建議以 C++ 的方式思考
    • include <cxxxx>
    • using namespace std::functionYouUsed
  • Reference: 

2017年12月28日 星期四

[C++] do...while(0)


  • 優點:
    • block 區塊, 可以在其內宣告變數, 在像 C89需要將變數定義在最上方這方面大有幫助
    • 以 do...while(0) 取代 goto, 將 goto 後的東西放 while外面, 裡面用 break來達到 goto的效果
    • 程式碼易讀且效能並沒損失
    • 避免 marco 沒有加 {}, 又接在 if() 單行執行內容有分號的 case
      • e.g. 
      • #define swap(x, y) int temp; temp = x; x = y; y = temp;
        if(x > y)
                   swap(x, y);
            
  • Reference:宏定义中使用do{}while(0)的好处

2012年12月17日 星期一

[Programming] 以單一空格取代重複空格

  1 #include <stdio.h>

  2 // This code transform multple blanks to single blank
  3 #define NONBLANK 'a'
  4
  5 int main(){
  6         int c=0;
  7         int lastBlank=NONBLANK;
  8         while((c=getchar())!=EOF){
  9                 if(' '!=c){
 10                         putchar(c);
 11                 }else{
 12                         if(lastBlank!=' '){
 13                                 putchar(c);
 14                         }
 15                 }
 16                 lastBlank=c;
 17         }
 18         return 0;
 19 }

[Programming] C用 printf印八進位與十六進位

利用 printf("%o %x", numOct, numHex); 可分別印出八進位與十六進位的數字