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?

4 Answers

6
Elroy Jetson On

It's because you are declaring the variables in an if statement.

Logically you may be of the belief that the else in a way guarantees that the variables will be assigned if the declaration is in both the if and also in the else block.

The correct way to do it is to just declare the variables before the if block, otherwise the variables use will be restricted to the scope from which it was declared.

Also, you can do this without the need for an if and else by using ternary operations:

        int a = 1;
        int b = 2;

        int c = a >= b ? a : b;
        int d = b < a ? b : a;

With this type of syntax, you can save yourself the hassle of writing if and else blocks for simple variable assignments. The variable after the ? is the result if the condition is true, and the variable after the : is the result if the condition is false.

29
Bathsheba On

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;
}
4
Cid On

That's a scope problem, you are creating the variables inside a scope and they can't be accessed outside

if (a >= b){
    int c = a;  // c and d belongs to that if scope
    int d = b;
}
else{
    int c = b;  // c and d belongs to that else scope
    int d = a;
}

Change your code to this :

a = 1;
b = 2;
int c;
int d;

if (a >= b){
    c = a;
    d = b;
}
else{
    c = b;
    d = a;
}
// You can now call c and d there

A way to shorten that code would be to store the boolean value of a >= b and use it in a ternary expression to set c and d

In example :

a = 1;
b = 2;
bool IsAGreaterOrEqualToB = (a >= b);
int c = ((IsAGreaterOrEqualToB) ? (a) : (b));
int d = ((IsAGreaterOrEqualToB) ? (b) : (a));
21
NathanOliver On

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.