Live data from Hacker News

Why 1 && 2 == 2

blog.chewxy.com

1–10 of 58 posts

Re: Why 1 && 2 == 2

#2
In C++,
    (cout 
...which is not an error, since the result of operatorDisambiguating the expression with parentheses should output 1 in every case.

Re: Why 1 && 2 == 2

#3
post #2

In C++, (cout ...which is not an error, since the result of operator Disambiguating the expression with parentheses should output 1 in every case.

I wrote the article (didn't plan on HN traffic, thanks Boyter). I've fixed it with your comment.

Thanks

Re: Why 1 && 2 == 2

#4
Thank god he didn't try php.

    echo 2 && 1; // 1
    echo 1 && 2; // 1
    echo 2 || 1; // 1
    echo 1 || 2; // 1
    echo 2 ?: 1; // 2
In php ?: is javascript's || Unfortunately there is no && that works correctly.

Re: Why 1 && 2 == 2

#6

Thank god he didn't try php. echo 2 && 1; // 1 echo 1 && 2; // 1 echo 2 || 1; // 1 echo 1 || 2; // 1 echo 2 ?: 1; // 2 In php ?: is javascript's || Unfortunately there is no && that works correctly.

Came here to say this. If you use var_dump you can see it's coercing the result to a bool.

    $ php -r 'var_dump(1 && 2);'
    bool(true)

Re: Why 1 && 2 == 2

#9
post #8
post #7

How did he get an expression that shouldn't involve any memory references to segfault?

I suck at C?

He probably thought pointers are the only kind of variables and that he needed to dereference them. I imagine something like

    int *a = 1, *b = 2;
    printf("%d\n", *a && *b);
Either that or he used `%s` as a format specifier. That seems more probable.

Edit: Or, as I just realised the people below me meant,

    printf(a && b);

Re: Why 1 && 2 == 2

#10
post #9
post #8

Earlier quoted context omitted.

I suck at C?

He probably thought pointers are the only kind of variables and that he needed to dereference them. I imagine something like int *a = 1, *b = 2; printf("%d\n", *a && *b); Either that or he used `%s` as a format specifier. That seems more probable. Edit: Or, as I just realised the people below me meant, printf(a && b);

Nah mate, it's just some compiler flag that I didn't turn on (don't know which. my gcc-fu is fail since it's been really a long time since I touched C)
Post reply on HN