Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I assign the value of one variable to another? [duplicate]

Tags:

c++

I have two variables and I want to work with the bigger and the smaller one differently.

My approach:

a = 1;
b = 2;

if (a >= b){
    int c = a;
    int d = b;
}
else{
    int c = b;
    int d = a;
}

I obtained an error of unused variable and when I try to use c and d later, it says

c could not be resolved

Is there a way to solve this?

like image 653
Laura Pinguicha Avatar asked May 03 '19 12:05

Laura Pinguicha


2 Answers

In both cases c and d are scoped to the braces in the if else block, so you can't access them outside that.

You need something of the form

int c, d;
if (a >= b){
    c = a;
    d = b;
} else {
    c = b;
    d = a;
}
like image 105
Bathsheba Avatar answered Dec 01 '22 20:12

Bathsheba


As other have pointed out the issue here is where you declare the variables. You cannot use them outside of the scope they are declared in so you get an error.

If you can use C++17 then you can fix the code by using std::minmax and a structured binding like

int main()
{
    int a = 5, b = 10;
    auto [min, max] = std::minmax(b, a);
    std::cout << min << " " << max;
}

which is really nice because now you don't have variables that are uninitialized for any amount of time.

like image 34
NathanOliver Avatar answered Dec 01 '22 19:12

NathanOliver