C Operator precedence

Share code examples or discuss embedded software, including device drivers, interrupt handlers, middleware and application code.

Moderators: Markus Girdland, Mattias Norlander

pmjagtap7
Posts: 2
Joined: Wed Oct 10, 2018 10:09 am

C Operator precedence

Postby pmjagtap7 » Wed Oct 10, 2018 10:17 am

Hello,

I have following simple statement with 3 different flavours.

Code: Select all

int i;
i = (uint16_t)(0x1F784 >> 16);      //1
i = (uint16_t) 0x1F784 >> 16;      //0
i = 0x1F784 >> 16;            //1


Even though >> operator has higher precedence than assignment(=) operator, 2nd statement produces i = 0; value.
Can someone help me understand what am I missing here ?


Thanks

User avatar
alberto.spagnolo
Posts: 2
Joined: Mon Jan 22, 2018 8:30 am

Re: C Operator precedence

Postby alberto.spagnolo » Fri Oct 19, 2018 3:49 pm

Hi,
cast hash higher precedence than both assignment and shift.
Thus:

Code: Select all

i = (uint16_t)(0x1F784 >> 16);      //1


0x1F784 defaults defautls to int, 32 bits. After shifting, you obtain 0x1 (still int, 32 bits). Then you cast to uint16_t, truncating the two upper bytes. Then you assign to an integer, that becomes 0x1.

Code: Select all

i = (uint16_t) 0x1F784 >> 16;      //0


0x1F784 defaults defautls to int, 32 bits. Then it gets cast to uint16_t, truncating the two upper bytes. Then you shift right by 16 bits, discarding everything and assigning a 0.

Code: Select all

i = 0x1F784 >> 16;            //1


I think that this one is clear, right? ;)
Anyway, I personally find a bit hard to remember all the precedences for different operators and I prefer to explicitly add round brackets that show the precedence.

Bye,
Alberto

pmjagtap7
Posts: 2
Joined: Wed Oct 10, 2018 10:09 am

Re: C Operator precedence

Postby pmjagtap7 » Fri Oct 19, 2018 5:24 pm

alberto.spagnolo wrote:Hi,
cast hash higher precedence than both assignment and shift.
Thus:

Code: Select all

i = (uint16_t)(0x1F784 >> 16);      //1


0x1F784 defaults defautls to int, 32 bits. After shifting, you obtain 0x1 (still int, 32 bits). Then you cast to uint16_t, truncating the two upper bytes. Then you assign to an integer, that becomes 0x1.

Code: Select all

i = (uint16_t) 0x1F784 >> 16;      //0


0x1F784 defaults defautls to int, 32 bits. Then it gets cast to uint16_t, truncating the two upper bytes. Then you shift right by 16 bits, discarding everything and assigning a 0.

Code: Select all

i = 0x1F784 >> 16;            //1


I think that this one is clear, right? ;)
Anyway, I personally find a bit hard to remember all the precedences for different operators and I prefer to explicitly add round brackets that show the precedence.

Bye,
Alberto



Ahh.. I forgot to consider prescedence of cast.

Thanks for throwing a light on it


Return to “Embedded target code development discussions”

Who is online

Users browsing this forum: Bing [Bot] and 2 guests