Setting an Integer from a if then statement

I am trying to get it so if i put a piece of code such as

if ((variable1 - variable2) < 0)
        int variable5 = (variable3 + variable4);

but this does not seem to work for me. So i was wondering if anyone had a solution?

Jon Skeet
people
quotationmark

You're trying to declare a variable as the only statement in an if statement body. That's not allowed, as it would be pointless - the variable would be out of scope immediately afterwards. Either you should declare the variable first:

int variable5 = 0; // Or whatever value you want otherwise
if (variable1 - variabl < 0)
    variable5 = variable3 + variable4;

Or if you only need the variable within the body of the if statement, you'll need more statements:

if (variable1 - variabl < 0) {
    int variable5 = variable3 + variable4;
    // Use variable5
}

I would strongly encourage you to always use braces with if statements (and loops etc).

people

See more on this question at Stackoverflow