如果陈述含糊不清

时间:2012-01-07 05:02:29

标签: c compiler-construction if-statement

我正在尝试编写自己的代码来遍历PATH,以便在C编程中找到可执行文件作为学习练习。 (成功后我可能会用别人的代码替换它,但现在我想了解我的错误。)

以下代码部分没有跳到我期望的else语句......

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define EXECUTABLE S_IXOTH /* executable by others */
#define MAX_PATH_LEN 1024

void message (const char *msg)
{
  fprintf(stdout, "INFO: %s\n", *msg);
}

int main (int argc, char *argv[], char *envp[])
{
  char *editor;
  struct stat editor_stat;
  char full_path[MAX_PATH_LEN];
  int found_path;

  memset(full_path,0,MAX_PATH_LEN);
  strcpy(full_path,"/bin/ed");
  found_path=stat(full_path,&editor_stat);

  if (found_path!=0) {
    editor=NULL;
    message("The EDITOR specified is not found in the PATH. Using default editor");
  } else {
    if (editor_stat.st_mode&EXECUTABLE==0) {
      editor=NULL;
      message("The EDITOR specified must have world execute permission. using default editoe");
    } else {
      editor=full_path;
    }
  }

}

当我使用gdb跟踪它时,我看到它跳转到第二个而不是第一个,并且不执行可执行检查...

(gdb) file /tmp/sample2
Reading symbols from /tmp/sample2...done.
(gdb) b 28
Breakpoint 1 at 0x400688: file /home/ken/c/shorter_sample.c, line 28.
(gdb) r
Starting program: /tmp/sample2 

Breakpoint 1, main (argc=1, argv=0x7fffffffe1f8, envp=0x7fffffffe208)
    at /home/ken/c/shorter_sample.c:28
28        if (found_path!=0) {
Missing separate debuginfos, use: debuginfo-install glibc-2.13-2.x86_64
(gdb) p found_path
$1 = 0
(gdb) s
36            editor=full_path;
(gdb) 

它应该跳到32行而不是36。

我已经尝试过这里的C模糊,我已经阅读了Kernighan&amp;的“C”部分。 Ritchie在C歧义下在索引中被引用,并且在代码中尽可能多地支持花括号,但编译器没有按照我的意图进行操作。

仅供参考,我在Fedora 14上使用内核2.6.35.14-106.fc14.x86_64的gcc-4.5.1-4.fc14.x86_64。

1 个答案:

答案 0 :(得分:7)

&的运算符优先级低于==;这意味着第二个if语句相当于:

    if (editor_stat.st_mode&(EXECUTABLE==0))

我要走出去,说EXECUTABLE不是0,这使if相当于:

    if (editor_stat.st_mode & 0)

    if (0)

第二个if声明应为:

    if ((editor_stat.st_mode&EXECUTABLE)==0)