像if(argv [1] [0]!=〜' t')这样的表达式的评估

时间:2017-01-26 13:33:15

标签: c if-statement

我必须输入一个字符串以使第二个if条件为false并打印"正确!"。可以吗?

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {

 if(argc != 2) { // argc is how long argv is, including that path-to-self
     puts("You need to give me exactly one argument!");
     return -1;

   }
// argv[1] represents the command line input you have given to the program. Which is a string or a char array.

 if(argv[1][0] != ~'t' || argv[1][1] != ~'h' || argv[1][2] != ~'e') {
      puts("noooo!");
      return 0;
    }
 else printf("Correct!\n");

 return 0;
}

1 个答案:

答案 0 :(得分:0)

如果一个参数传递给程序(即第一个argc != 2检查没有失败)那么表达式argv[1][0] != ~'t'总是为真(以及其他检查但由于short-circuit evaluation而不会进行检查。

表达式~'t'将首先转换为intsee this reference for why,同样的事情将发生在argv[1][0])。这意味着您将拥有~0x00000074(如果使用ASCII alphabet和32位int)。这将评估为0xffffff8b

您为程序提供的参数无关紧要,argv[1][0] 永远不会等于0xffffff8b,因此条件为真。

相关问题