Consider the following code:
#include
using namespace std;
int main()
{
int x, y, i;
cin >> x >> y >> i;
swit
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.