Tag: Operator Precedence

  • C++ Precedence And Associativity

    當你有算數的經驗時,你會知道在做四則運算時會有先乘除後加減的規則

    程式當然也有,C++ 裡面也有相關的先後順序與關聯性

    C++ Precedence and associativity

    先前觀念

    What is the purpose of {} in C++?

    {} can be used to initialise variables in C++11 in the same way that they are used to initialise arrays and structures in C.

    {} 可用於將C++ 已宣告的變數做 初始值代入。

    範例01

    #include <iostream>
    
    
    int main(){
    
    //初始值代入
        int a {6};
        int b {3};
        int c {8};
        int d {9};
        int e {3};
        int f {2};
        int g {5};
            
        int result = a + b * c -d/e -f + g; //  6 +  24  -   3 - 2 + 5
        
        std::cout << "result : " << result << std::endl;
    
        system("pause");
    
        return 0;
    }
    
    //結果:  6 +  24  -   3 - 2 + 5 = 30

    範例02

    #include <iostream>
    
    
    int main(){
    
        int a {6};
        int b {3};
        int c {8};
        int d {9};
        int e {3};
        int f {2};
        int g {5};
            
        int result = a + b * c -d/e -f + g; //  6 +  24  -   3 - 2 + 5
        
        std::cout << "result : " << result << std::endl;
    
        result = a/b*c +d - e + f;  //   16 + 9 - 3 + 2
        std::cout << "result : " << result << std::endl;
    
        system("pause");
    
        return 0;
    }
    
    //結果:  6 +  24  -   3 - 2 + 5 = 30
    //結果:   16 + 9 - 3 + 2 =24