1

I am getting warning in my c file when I try to use >> operand.Anyone who can tell me what does it mean?

[code]:

 new_elem = (Elem *) realloc(pl->elem, (pl->size + (pl->size >> 1)) * sizeof(Elem));

[warning]:

Clang-Tidy use of a signed integer operand with a binary bitwise operator.
Keren Caelen
  • 1,466
  • 3
  • 17
  • 38
Reed Chan
  • 525
  • 6
  • 16
  • 3
    Possible duplicate of [Are the results of bitwise operations on signed integers defined?](https://stackoverflow.com/questions/11644362/are-the-results-of-bitwise-operations-on-signed-integers-defined) – Gaurav Sehgal May 07 '18 at 10:00
  • The question for me is why do you do it? A division by 2 would be nicer there to my mind. And If `pl->size == 1` I am not sure you get what you want. – Kami Kaze May 07 '18 at 10:16
  • In c, you should avoid cast pointer explicitly in malloc/realloc – Chen Li May 07 '18 at 10:34
  • tl;dr: You used `int` for pl->size but you should have used `size_t` instead. – Lundin May 07 '18 at 11:20
  • @陳力 I got it, thanks a lot! – Reed Chan May 07 '18 at 11:54

1 Answers1

2

In C, if a variable is a signed integer, then the binary bitwise operator >> on it is implementation dependent (you shouldn't rely on it). See this post as Gaurav suggested in comments.
In your exmaple, pl->size is (guessing!) a signed integer, and you do (pl->size >> 1), so you apply a binary bitwise operator >> on pl->size variable. Clang tries to warn you about an implementation defined behavior, so you can fix your code.
Use division and multiplication on signed integers, which is well defined. The compiler should optimize the code anyway.

new_elem = realloc(pl->elem, (pl->size + (pl->size/2)) * sizeof(Elem));
KamilCuk
  • 120,984
  • 8
  • 59
  • 111