Morchul
Morchul

Reputation: 2037

Assign last value of if else statement to variable

I know that you can assign a variable like this:

double y = 140;
int i = (y > 100) ? y / 2 : y * 2; //shorthand if else
std::cout << i << std::endl;  // 70

Or for multiple commands seperated with a ,:

double y = 140;
int i = (y > 100) ? (y /= 2, 5) : (y *= 2, 10);
std::cout << i << std::endl; // 5
std::cout << y << std::endl; // 70

But can I do this with a normal if else statement?

I tried this:

int i = if(y > 100){
            y / 2;
        } else {
            y * 2;
        }

Or with the whole if statement in { if..} brackets but that doesn't work.

Is it possible to do it with a normal if else statement in which the last expression the value is which assign to the variable (without a method, function or lambda)?

Upvotes: 0

Views: 101

Answers (3)

Shubham Chopra
Shubham Chopra

Reputation: 1737

You can approach this way:-

#include<iostream>
using namespace std;
int main()
{
    double y = 140;
    int i;
if(y > 100){
        y =y/2;
        i = 5; 
    } else {
        y =y*2;
        i = 10;
    }
    cout<<i<<endl;
    cout<<y<<endl;
return 0;
}

The below code snippent won't work because if does not return anything, it's just a statement.

 int i = if(y > 100){
                y / 2;
            } else {
                y * 2;
            }

Upvotes: 0

Quentin
Quentin

Reputation: 63154

No, this is not possible within your limitations. For the record, the lambda solution looks like this:

int i = [&]{
    if(y > 100) {
        return y / 2;
    } else {
        return y * 2;
    }
}();

Upvotes: 5

nvoigt
nvoigt

Reputation: 77354

No it's not possible. An if does not return anything, it's a flow control statement. If you want to do it, you'd have to do it "manually":

int i;

if(y > 100){
        y /= 2;
        i = 5; 
    } else {
        y *= 2;
        i = 10;
    }

Upvotes: 0

Related Questions