问题
I know I'm not very good in C but I thought that I could get this right:
if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0)
type comes as a char* and I've tested this code with the first part of the condition.It works well.If I have the second part of the condition and my type contains "in" it's ok but if all three conditions are available,if i input "out",the if isn't skipped.Why's that?
回答1:
your code:
if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0){
" your code-1"
}
else{
" your code-2"
}
Is equivalent to:
if(strlen(type) == 0 ){
" your code-1"
}
else{
if(strcmp(type,"in")!=0){
" your code-1"
}
else{
if(strcmp(type,"out")!=0){
" your code-1"
}
else{
" your code-2"
}
}
}
Point is if you have first if() executes if string type have something, then else never executes. Because a empty string(in else part) can't be equals to "in" or "out". So you always have choice to execute "code-1" if string is not empty and nothing to executes if string is empty (that is length = 0).
Edit:
I think you wants something like if type string is "in" then execute "code-1" if type is "out" then execute second code-2. like:
if(strlen(type) == 0 ){
}
else{
if(strcmp(type,"in")!=0){
" your code-1"
}
else{
if(strcmp(type,"out")!=0){
" your code-2"
}
}
}
you can do like:
flag = 'o';// this will save string comparison again
if(strlen(type) == 0 || strcmp(type,"in")==0 ||
strcmp(type,"out")!=0 && !(flag='?')){
"code-1"
}
else{
if(flag=='o'){ //no strcmp needed
"code-2"
}
}
Here I posted a Code based on my logic and it run as:
:~$ ./a.out
Enter string: in
in
:~$ ./a.out
Enter string: out
out
:~$ ./a.out
Enter string: xx
:~$
回答2:
The branch will be taken if type is empty, or if type contains either "in" or "out".
Given the expression a || b, the following are true:
- Operands are evaluated left-to-right, meaning
ais evaluated first; - if
aevaluates to non-zero (true), then the entire expression evaluates to true, andbis not evaluated; - if
aevaluates to zero (false), thenbis evaluated; - if both
aandbevaluate to zero (false), then the entire expression evaluates to false; otherwise, the expression evaluates to true;
So if type contains the string "out", then
strlen(type) == 0evaluates tofalse, meaning we evaluatestrcmp(type, "in") != 0, which evaluates tofalse, meaning we evaluatestrcmp(type, "out") != 0, which evaluates totrue, so- the branch is taken
Based on what you say you're expecting, it sounds like you got the sense of the last test wrong, and that you really want
if( strlen( type ) == 0 ||
strcmp( type, "in" ) != 0 ||
strcmp( type, "out" ) == 0 )
{ // ^^ note operator
...
}
This will enter the branch if type is empty, if type contains "in", or if type doesn't contain "out".
来源:https://stackoverflow.com/questions/15885715/c-logical-or-in-if