Reputation: 429
I am trying to multiply an integer by 5 using bitwise operations. But there seems to be a bug in my code that I can't identify. Here's my code
#include <stdio.h>
#define print_integer(exp) printf("%s : %d\n", #exp, (exp))
int multiply(int num) {
int ans;
ans = num << 2 + num;
return ans;
}
int main() {
int a = 1, b = 2, c = 3;
print_integer(multiply(a));
print_integer(multiply(b));
print_integer(multiply(c));
return 0;
}
Edit:- The bug is in line ans = num << 2 + num;
Upvotes: 3
Views: 1817
Reputation: 144780
The precedence between <<
and +
is counter intuitive. Use parentheses and compile with -Wall
to get useful warnings abut this kind of potential mistake:
#include <stdio.h>
#define print_integer(exp) printf("%s : %d\n", #exp, (exp))
int multiply(int num) {
return (num << 2) + num;
}
int main(void) {
int a = 1, b = 2, c = 3;
print_integer(multiply(a));
print_integer(multiply(b));
print_integer(multiply(c));
return 0;
}
Upvotes: 3
Reputation: 19
You are adding the num after the change ( num<<2 ) , set a temp value for num .
int tmp = num ;
ans = num << 2 + tmp ;
Upvotes: -1