Easier way to check if expression is true?

Jul 23, 2012 at 9:05am
closed account (3bfGNwbp)
There has to be an easier way to do this.

Like instead of:
 
if(player == array[i][x] && player == array[i][x+1]) 


We should be able to do this:
 
if(player == (array[i][x] && array[i][x+1]))


Is there a way to do something like that? It's a pain to have to type that all.
Jul 23, 2012 at 10:27am
The short answer is no. The longer answer is you'll have to make it yourself via a macro or function.


If this
if(player == (array[i][x] && array[i][x+1]))
was the same as this
if(player == array[i][x] && player == array[i][x+1])

how would I actually check if player was the same as the result of (array[i][x] && array[i][x+1])? I'd have to do something like this:

1
2
3
bool resultToCheckAgainst = (array[i][x] && array[i][x+1]);
if (player == resultToCheckAgainst )
{ ...


It'd be a mess, not least because at first reading
1
2
3
bool resultToCheckAgainst = (array[i][x] && array[i][x+1]);
if (player == resultToCheckAgainst )
{ ...

looks like it should be identical to
if(player == (array[i][x] && array[i][x+1]))
Last edited on Jul 23, 2012 at 10:31am
Jul 23, 2012 at 10:37am
No, not really, the first line is the syntax you have to use.
The only way around this you may want to use if you have more than 2 comparisons you have to make is to use a for loop instead, accumulating the result:

1
2
3
4
5
bool result = true;
for (int j = i; j <= i + 10 && result; ++j) {
    result = player == array[j][x]; 
    // or result = result && (...) if you feel safer with that, but it's essentially the same
}  


You can also write a macro to handle that, but honestly I don't see a really good reason to go through with this.
Jul 23, 2012 at 10:42am
I'm afraid not. You must remember how logical operators work, and that the if() statement checks for a nonzero value. Also remember precedence. Remember that logical operators are functions in syntaxic sugar.

if(player == (array[i][x] && array[i][x+1]))

It first checks to see if the following are nonzero: array[i][x], array[i][x+1]
If they are, boolean TRUE is returned, if not, FALSE.

Then, it compares whether that is equal to player. You are comparing player to a boolean value, which I doubt you want.

Jul 23, 2012 at 12:14pm
The short answer is no, however, I would question your data organization.

What are you trying to represent by array[i][x] and array[i][x+1]) ?
If array is a game map it would appear you're checking if a player is in two locations.
It's also not clear what i and x are supposed to represent.

With better data organization, I suspect you would both a much short and much clearer if statement. Have you considered representing your data in structs?




Topic archived. No new replies allowed.