3

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;

Codor
  • 17,235
  • 9
  • 32
  • 52
Sanjay-sopho
  • 429
  • 3
  • 15

2 Answers2

3

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;
}
chqrlie
  • 114,102
  • 10
  • 108
  • 170
-1

You are adding the num after the change ( num<<2 ) , set a temp value for num .

int tmp = num ; 
ans = num << 2 + tmp ;