gdgrana: (argh)
[personal profile] gdgrana
I feel REALLY stupid for asking this, as I'm sure the answer is right in front of me, but for the life of me I can't figure this out.

How do I properly code up nested arguments for an "if" statement?

Example: two variables "varA" and "varB" have been assigned their values. I want to check what those values are before acting on the rest of the script: specifically, "varA" should be some value "foo" AND "varB" should be neither "bar" or "baz".

Here's how I thought it should go:

if (varA == "foo") && ( (varB != "bar") || (varB != "baz") )
{
do something;
}

When I do this, though, it seems to ignore the "varB" stuff and only acts on all instances where "varA" is "foo". The problem must be in how I nest the "varB" conditions, since if I remove one of them and fix the parenthesis accordingly, it works for that value of "varB". I have no idea how to make it work for my needs, however.

Thanks for y'alls input.


EDIT: Figured it out. Boolean fail on my end >|

Date: 2010-03-20 04:21 pm (UTC)
From: [identity profile] kane-magus.livejournal.com
Yeah, as it seems you already figured out, in that example it would've only checked to see if varB were not "bar" and if not it would have returned true without checking the second part even if it was "baz," or if it was "bar" it would still be true because it isn't "baz". Also, you don't even really need to nest it, not that it hurts much to do so. Just change the || to another && and take out the nested parentheses, and it should still work.

In my own stuff over the years I have lost untold hours due to simple stuff like that.

Date: 2010-03-20 04:29 pm (UTC)
From: [identity profile] kane-magus.livejournal.com
Or if you wanted to leave it similar to what you originally had, you could do something like

if varA == "foo" && !(varB == "bar" || varB == "baz")

Date: 2010-03-21 04:45 am (UTC)
From: [identity profile] david-grana.livejournal.com
I ended up going this route, yes. I dunno, I like keeping them nested just for simplicity's sake; keeping the varB arguments together helps a bit with sanity checks.

But yeah, I'd forgotten the most basic of logic design elements, and things like that are only slightly more annoying than forgetting something like a semicolon -_-

Profile

gdgrana: (Default)
David

August 2010

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
29 3031    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 3rd, 2025 04:22 pm
Powered by Dreamwidth Studios