Joey
Joey

Reputation: 809

unix goto command source code

Here is the source code of a historical Unix goto.c: http://v6shell.org/history/goto.c

So we're trying to find a matching label recording the "goto label" call.

My problem:

if (getlin(line)) {
        write(1, "label not found\n", 16);
        return;
        }

So I would expect if getlin() returns true we should print out "label not found" and exit the program.

But look at this:

getlin(s)
char s[];
{
    int ch, i;

    i = 0;
l:
    if ((ch=getc())=='\0') return(1);
    if (ch!=':') {
        while(ch!='\n' && ch!='\0')
            ch = getc();
        goto l;
        }
    while ((ch=getc())==' ');
    while (ch!=' ' && ch!='\n' && ch!='\0') {
        s[i++] = ch;
        ch = getc();
        }
    while(ch != '\n')
        ch = getc();
    s[i] = '\0';
    return(0);
}

getlin() will return 0(true) if we found the label and 1(false) if we didn't.

But it should be the other way around or we would need to say:

if (**!** getlin(line)){}

What is wrong here?

Upvotes: 1

Views: 178

Answers (1)

Hari Menon
Hari Menon

Reputation: 35405

0 is treated as false in C. Hence the confusion. You can try out by running this small sample of code:

#include <stdio.h>

int i = 0;

int main() {
  if(i) {
    printf("i is %d and it is true\n", i);
  } else {
    printf("i is %d and it is false\n", i);
  }
  return 0;
}

As an exit code, 0 is considered SUCCESS. But in conditionals (in C), 0 evaluates to false and 1 evaluates to true.

But, in bash, 0 is considered true, even in conditionals. That is because it was more convenient that way in most use cases for bash, since we are always dealing with processes.

Upvotes: 3

Related Questions