What are the signs of crosses initialization?

后端 未结 4 1123
谎友^
谎友^ 2020-11-28 03:28

Consider the following code:

#include 
using namespace std;

int main()
{
    int x, y, i;
    cin >> x >> y >> i;
    swit         


        
4条回答
  •  鱼传尺愫
    2020-11-28 04:09

    I suggest you promote your r variable before the switch statement. If you want to use a variable across the case blocks, (or the same variable name but different usages), define it before the switch statement:

    #include 
    using namespace std;
    
    int main()
    {
        int x, y, i;
        cin >> x >> y >> i;
    // Define the variable before the switch.
        int r;
        switch(i) {
            case 1:
                r = x + y
                cout << r;
                break;
            case 2:
                r = x - y;
                cout << r;
                break;
        };
    }
    

    One of the benefits is that the compiler does not have to perform local allocation (a.k.a. pushing onto the stack) in each case block.

    A drawback to this approach is when cases "fall" into other cases (i.e. without using break), as the variable will have a previous value.

提交回复
热议问题