开发者

If statement not seeming to check other && in statement

开发者 https://www.devze.com 2023-03-14 20:43 出处:网络
I have an if statement that looks as follows: int count=0; string Check; if ((count==4 && Check!=\"-s\")||(count==4 && Check!=\"-S\"))

I have an if statement that looks as follows:

int count=0;
string Check;

if ((count==4 && Check!="-s")||(count==4 && Check!="-S"))

If count equals 4 and Check equals "-s" or "-S" it still enter开发者_JAVA百科s this if statement because of the count == 4. It totally seems to ignore the second part. Is there something I'm doing wrong?


It's always going to be the case that either Check!="-s" or Check!="-S". Hence, your if statement is equivalent to if (count==4).


Well, if Check is "-S", then it will not even check the second pair of conditions, because you check with ||. The same holds true for the opposite case. If one is false, the other is true. Replace that with a &&.

int count = 4;
string Check = "-S";

if( (count == 4 && // count is 4, alright.
     Check != "-s") || // Check is "-S", alright I'm done thanks to || (OR)
    (count == 4 &&
     Check != "-S") )
{
  // ...
}

int count = 4;
string Check = "-s";

if( (count == 4 && // count is 4, alright.
     Check != "-s") || // Check is "-S", time to check the other condition pair...
    (count == 4 && // count is 4, alright.
     Check != "-S") ) // Check is "-s", which is different from "-S", perfect.
{
  // ...
}

Now the corrected version:

int count = 4;
string Check = "-S";

if( (count == 4 && // count is 4, alright.
     Check != "-s") && // Check is "-S", different from "-s", now on to the other condition!
    (count == 4 && // count is 4, alright.
     Check != "-S") ) // Check is "-S"... oh dang! No executed code for you.
{
  // ...
}


If count == 4 and Check == "-s", then the expression to the right of the || is true. If count == 4 and Check == "-S", then the expression to the left of the || is true. So you have true or true which is true. Thus, your if-block is executed.


The right statement is:

if(count==4 && (Check != "-s" || Check!="-S"))

The statement that you wrote is true if you have count = 4 and Check = "-S" because then the first part of the OR is true.


Might be more clear to use:

if (count==4 && Check!="-s" && Check!="-S")


You should use !strcmp(Check, "-s") and !strcmp(Check, "-S") instead of !=.

If you use == you compare the pointers and that is no what you want. The pointers will always be different thus your second argument will always be true.


You want to enter the if body if and only if Check is != from either -s or -S and count is = 4 right?

if ( (Check!="-s" && Check!="-S") && count==4 ) 

should work.

or

if ( Check.tolower() !="-s" && count==4 ) 

should work.

(Do not remember the name of the function to lowercase a string, you have got to look it up)

Hope this help.

0

精彩评论

暂无评论...
验证码 换一张
取 消