Thanks for your explanation. I do understand now how '1 << 31' could cause a potential problem.
On Fri, Jan 8, 2021 at 6:10 AM Nico Huber nico.h@gmx.de wrote:
Hi Harshit,
On 08.01.21 01:35, Harshit Sharma wrote:
Although, I agree that 1u << 31 is much better, I believe 1 << 31 is not wrong either as long as it is assigned to an 'unsigned int' as the
compiler
performs an implicit conversion from a lower data type to a higher data type ('int' to 'unsigned int' in this case).
you are right about the implicit conversion, but this happens too late. The actual error may happen before the conversion. I guess mostly because of the way signed numbers are handled in assembler, compilers usually produce code that results in -2^31 for `1 << 31`. This -2^31 then implicitly converted to an unsigned is 2^31 which is what we usually intend.
But the theoretical problem is what happens if the compiler produces code that does not result in -2^31 for the signed number. As the C standard implicitly says `1 << 31` is undefined, the compiler can basically do what it wants and would still be C compliant.
Nico