-2

In given code, a bool has been passed on to foo as shown in mainFunc. I am not sure if e >> 24 is a right thing to do in foo. I believe this will only give garbage values.

void foo(bool e){
   int a;
   bool s;
   e = e >> 24;
   ...
}

void mainFunc(){
   int *arg = (int*)malloc(sizeof(int));
   *arg = xxxx;   

   foo(*(bool*)arg);
}

Is this a right thing to do?

EDIT: I was more concerned about operation e >> 24, since e is bool. won't this lead to any issue? Apologies for any misunderstanding.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • I can't really make sense of the question. The same thing happens to the other 3 bytes as happens to the fourth byte -- nothing at all. When you convert "three" to "3", nothing happens to the "three" -- it stays precisely the same. You just also have a "3' to do things with. – David Schwartz Oct 07 '19 at 09:46
  • if `sizeof(bool)` is 1, there are no "other 3 bytes" – kmdreko Oct 07 '19 at 09:47
  • 0 is false, all other values are true. It's not like only the low 8 bits of the int are used in the conversion... – Shawn Oct 07 '19 at 09:47
  • I am not sure if `e >> 24` is a valid command to use. since e is bool. – Prabhsimrandeep Singh Oct 07 '19 at 09:52
  • 1
    So, just to confirm, the question implied by the title, the question implied by the first paragraph, and the question implied by your `mainFunc` - _none_ of these are what you actually wanted to ask? Just remove them and ask a single question! – Useless Oct 07 '19 at 10:02
  • I'll edit the question for you if you want, so long as you confirm my understanding is right. – Useless Oct 07 '19 at 10:06
  • @Useless I have updated the question now? – Prabhsimrandeep Singh Oct 07 '19 at 10:14
  • And yet the title and more than half of the code are still irrelevant, as far as I can see. Is it really just the right-shift you're interested in? – Useless Oct 07 '19 at 11:06

2 Answers2

1

I was more concerned about operation e >> 24, since e is bool. won't this lead to any issue?

Built-in arithmetic operators do not operate on types smaller than int, see integral promotion for more details. In expression e = e >> 24; e is bool and to shift it right the compiler first promotes the value of e to int, does the shift and then converts the result back to bool. The result is always int 0, which gets converted to bool false. Unless the sizeof(int) <= 3, in which case shifting it 24 bits or more is undefined behaviour.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

The cast to bool just creates a new boolean value to pass to foo. Nothing at all happens to any of the four bytes that arg points to. They remain precisely the same.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278