code

What is the answer and why?

1
2
3
4
5
6
7
8
9
10
11
   #include <iostream>
    using namespace std;
   
    int fun(int p1=1, int p2=1){
        return p2<<p1;
    }
    int main(){
        cout<<fun(fun(),fun(2));
        return 0;
        
    }
http://ideone.com/
http://coliru.stacked-crooked.com/
Or click the gear icon in your post.
Last edited on
fun() is fun(1,1);

1<<1 is 0b10 or 2 in decimal.

Therefore:
fun( fun(), fun(2) ) is fun( 2, fun(2) )

fun(2) is fun(2,1);
1<<2 is 0b100 or 4 in decimal.

Therefore:
fun( fun(), fun(2) ) is fun( 2, 4 );

fun(2, 4) = 4 << 2 = 0b100 << 2 = 0b10000 = 16 in decimal

The answer is 16.


The << operator in line 5 is the bitwise shift left operator. It left-shifts the binary representation of p2 by p1 bits.

Here is a step-by-step walkthrough of 5<<3 :

5 << 3
0b00000101 << 3
0b00001010 << 2
0b00010100 << 1
0b00101000 << 0
40

So 5 << 3 gives a value of 40.
Thanks buddies, great help
Topic archived. No new replies allowed.