Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this bitwise operation return 30 instead of 384?

I am using Dev-C++ compiler. This program is supposed to print 30 but its printing 384.

#include <stdio.h>

int main() {
    int n = 3;
    int ans;

    ans = n<<3 + n<<1;
    printf("%d", ans);

    getch();
    return 0;
}
like image 896
Shyam Avatar asked Jan 10 '23 09:01

Shyam


1 Answers

The problem is that the + operator has higher precedence than the << operator. What you wrote actually means:

ans = n << (3 + n) << 1;

What you actually want is:

ans = (n<<3) + (n<<1);
like image 61
Rudy Matela Avatar answered Jan 22 '23 05:01

Rudy Matela