The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+1 vote

What will be returned by the following function foo when called as foo(10)?

int foo(int n)
    return n & n | 1;
asked in Programming by Veteran (396k points)
retagged by | 314 views

2 Answers

+5 votes
Best answer
& : Bitwise AND operator
| : Bitwise OR operator

int foo(int n)
    return n & n | 1;

return n & n | 1;
here precedence of &>| so n&n will be executed 1st.
n&n = n
Now, n|1 which is nothing but n+1 for even n (least bit 0) and n for odd n.

For foo(10), 11 will be output.
answered by Veteran (59.8k points)
edited by
can you please explain binary operations in some detail ?


I think we cant say here :-> foo(int n) it will return n+1 as ur statement ( n|1 which is nothing but n+1.) is seeming me wrong.

Bcz suppose  n=11 means foo(11)


now n|1=00001011 | 00000001 = 00001011=n=11 itself.

so foo(11) will return 11 ; not 12.

plz correct me :)

yes, you are correct..
0 votes
foo will return 11

because 10 &10 will return 10

and logical OR will return 10I1 means 10+1=11
answered by (111 points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,121 questions
53,242 answers
70,481 users