Semantics of `printf(“…”) || printf(“…”) || printf(“…”)`

后端 未结 3 1563
太阳男子
太阳男子 2021-01-29 11:39

I\'m wondering what the following statement will print in C?

printf(\"hello\\n\") || (printf(\"goodbye\\n\") || printf(\"world\\n\"));

I\'m usu

3条回答
  •  死守一世寂寞
    2021-01-29 12:29

    It will print:

    hello\n (that is, hello and a newline, not the literal "\n".)

    printf returns the number of characters printed to the console. The || is a short-circuiting "or", which means: do the first thing, then if the first thing returned "false", do the next thing. At the end, return back whether any of the things you did returned "true".

    In c, an int is considered "true" if it is any value other than 0, and all three of those printf calls print more than 0 characters, so it will run the first one, which returns (a value logically equivalent to) true, so it will stop execution of that line and go onto the next.

    Of course, there's no reason to ever write code like that... there are sometimes reasons to use short-circuiting boolean operators with functions that have side-effects (like printing to the console), but I can't think of a reason you'd ever need to short-circuit where the functions you were calling were being passed constants and you always knew exactly what result you would get from them.

    Also, yes, as written there's a compile error because of an extra open-parenthesis before your second printf. But ignoring that.

提交回复
热议问题