srishti raj
srishti raj

Reputation: 11

C bitwise operator '&' uses

#include<stdio.h>
main()
{
 (5%5)?1:0&puts("fizz");

}

The code above prints fizz as expected. But I don't understand how the bitwise & operand works with 0&puts("fizz"). What is the working behind it? What is the value of the expression?

Someone please explain

Upvotes: 1

Views: 163

Answers (6)

alk
alk

Reputation: 70931

The & forces the puts() to be excuted.

Upvotes: 0

tangrs
tangrs

Reputation: 9930

  1. (5%5) is evaluated to 0 which is false.
  2. The whole statement then evaluates to 0&puts("fizz");
  3. To evaluate that, the value 0 is bitwise AND'd with the return value of puts which can only be found by executing the function which prints fizz.
  4. The result (which will always be 0) is discarded.

Upvotes: 4

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

The expression:

(5 % 5)?    1  : 0 & puts("fizz"); 
   ^              ^      
   0 == False     executes 

puts prints: "fizz". The returned value from puts function is bitwise & with 0 and result (that should be 0) is discarded.

So your expression is equivalent to (5 % 5)? 1 : puts("fizz"); in effects.

Upvotes: 3

Thanushan
Thanushan

Reputation: 532

The puts() returns a non-negative number when sucessful. if (5%5) will return false. Therefore, the return value from puts() is bitwise & with 0.

Upvotes: 0

AlexJ136
AlexJ136

Reputation: 1282

The puts() function returns a non-negative number if it completes successfully. This non-negative number is then ANDed with the zero.

Upvotes: 0

unwind
unwind

Reputation: 399833

Well ... 5 % 5 is 0 (false), so the ?: part goes on to evaluate the expression to the right of the colon.

That means evaluating 0 bitwise-and:ed with the return value of puts(), so obviously the function must be called.

Upvotes: 2

Related Questions