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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With