2020年5月23日 星期六

C/C++ - Const

const 基本用途


    告知編譯器這個值為「常數」無法被修改。
  • 一般作用
        const int index = 5;
        index = 8; // error: assignment of read-only variable 'index'
  • 作用於 *
        // const pointer
        char * const constptr = initptr;
        *constptr = 1;              // 改變其 value OK
        constptr = otherptr;        // 改變其  addr Error
    
        // const value
        const char * constval = "const value";
        *constval = "nomal value";  // 改變其 value Error
        constval = otherptr;        // 改變其  addr OK
    
        // const pointer & const value
        const char * const consteverything = "ulti - const";

const 常見用途 : const&

在 C++ 可能常常看到 void function (type_Name const&);
"type_Name const&" 是可以寫成 "const type_Name &"
    int i = 10;
    const int &r = i;   // reference to const
    ++i;                // i 仍然可以修改
    ++r;                // r 不行 (expression must be a modifiable lvalue)
    通常追求效率的 C++ 工程師,會選擇 pass by reference 來防止程式做不必要的 Copy,這時 const 通常就會出現,來確保原始 value 不會被亂改。且 const 的出現可以使 call function 時,使用 rvalue。
    std::vector mySort(std::vector const &str)
    {
        std::vector r(str);
        std::sort(r.begin(), r.end());
        return r;
    }
    mySort({"abc", "def", "xyz"});

相關文章 :
C/C++ - 左值、右值 ( lvalue、rvalue )
讀書心得 - C++ Primer (5th Edition) - Chapter 2 (2)

參考資料 :

Related Posts:

  • C 語言 - size_t 及各個常見類型 typedef unsigned int size_t // 通常定義在 stddef.h int8 : -128 ~ 127 int16 : -32768 ~ 32767 int32 : -2147483648 ~ 2147483647 int64 : -9223372036854775808 ~ 9223372036854775807 uint8 : … Read More
  • BCB OLE操作EXCEL(3)在用 OLE 操作 Excel 時 有可能會遇到剪貼簿裡的資料過大 導致關閉 Excel 時跳出視窗警告 "是否放棄剪貼簿裡的資料" 要避開的話通常會用關閉 DisplayAlert 的方法來避免 但我常常失敗,原因不明。 所以給失敗的朋友另一個辦法 在 Excel 關閉前複製一格 避免剪貼簿裡資料過多跳出視窗 void __fastcall Excel::Close_2(){ Exc.Range = Exc.WorkSheet.… Read More
  • C 語言 - struct array 初始化 ( Initializing array of structures ) 初始化 struct array struct student { char* name; int grade; int id; }; 1. 依照當初宣告的順序 struct student myStudents[] = { {"Henry", 3, 1}, {"Marry", 3, 2} }; 1. 依照當初宣告的名子 … Read More
  • C 語言 - warning: left shift count >= width of type warning: left shift count >= width of type     一般來說,就是 shift 的 bit 大於資料型態的 bit 數。但有時使用 unsigned long 仍然會出錯,因為 unsigned long 會依照系統的不同,有時是 32 bit 有時是 64 bit,所以這時用 unsigned long long 較為安全 ( 保證 64 bit… Read More
  • C 語言 - #ifndef #ifndef 用途 在 .h 檔確保只會被編譯一次 #ifndef HELLO_H // 有些人會定義成 _HELLO_H_ #define HELLO_H // 但目的就是不會被重複編譯 #include <stdlib.h> int helloIntro(char** str); int main() __attribute__((weak)); #endif … Read More

0 意見:

張貼留言

Popular Posts