a pattern recognition program must print lines containing patter if input find pattern. if input find -x pattern, program must print lines except lines containing pattern.
// ..... switch(c) { case 'x': except=1; break; // ...... } // ...... while(getline(line,maxline)>0) { line_num++; if( (strstr(line,*argv)!=null) != except) { if(number) printf("%ld:",linenum); printf("%s",line); found++; } } // ......
in above code k&r except can either 1 or 0. how if(strstr...)
block functions handle -x ?
the logic simple. if pattern "-x"
should print lines not contain pattern.
for pattern except
equal 1
.
so lines contain pattern satisfy condition
strstr(line,*argv)!=null
that condition equal 1 if line contains pattern.
thus if except
equal 1 , condition strstr(line,*argv)!=null
equal 1 should skip pattern.
otherwise if condition strstr(line,*argv)!=null
not equal 1 if pattern not found if statement
if( (strstr(line,*argv)!=null) != except)
yields true , compound statement executed.
on other hand if except
equal 0
achieve condition in if statement evaluate true need condition strstr(line,*argv)!=null
equal 1.
in fact can rewrite if statement
if( (strstr(line,*argv)!=null) != except)
the following way
if( ( ( strstr(line,*argv) != null ) == 1 && except == 0 ) || ( ( strstr(line,*argv) != null ) == 0 && except == 1 ) )
shortly speaking if statement work if either
1 , 0
or
0 , 1
if either
1 , 1
or
0 , 0
then if statement not executed.
here 1 , 0 results of evaluating of 2 sub expressions in if statement.
Comments
Post a Comment