c++ - Is right-shifting an unsigned integer by its total number of bits UB ? -


this question has answer here:

i wanted check big calculated memory needs (stored in unsigned long long) compatible memory model used compile code.

i assumed right-shifting needs number of bits in pointer result in 0 if , if memory needs fit in virtual address space (independently of practical os limitations).

unfortunately, found out unexpected results when shifting 64 bit number 64 bits on compilers.

small demo:

const int ubits =  sizeof (unsigned)*8;  // number of bits, assuming 8 per byte const int ullbits =  sizeof (unsigned long long)*8;  cout << ubits << " bits unsigned\n";  cout << ullbits << " bits unsigned long long \n";  unsigned  utest=numeric_limits<unsigned>::max();  // big numbers unsigned long long ulltest=numeric_limits<unsigned long long>::max();  cout << "unsigned "<<utest << " rshift " << ubits << " = "     << (utest>>ubits)<<endl;  cout << "unsigned long long "<<ulltest << " rshift " << ullbits << " = "     << (ulltest>>ullbits)<<endl;  

i expected both displayed rshit results 0.

this works expected gcc.

but msvc 13 :

  • in 32 bits debug: 32 bit rshift on unsigned has no effect ( displays original number) 64 bit shift of unsigned long long 0 expected.
  • in 64 bits debug: rshift has no effect in both cases.
  • in 32 , 64 bits release: rshif 0 expected in both cases.

i'd know if compiler bug, or if undefined behaviour.

according c++ standard (5.8 shift operators)

  1. ...the behavior undefined if right operand negative, or greater or equal to length in bits of promoted left operand

the same written in c standard (6.5.7 bitwise shift operators)

3 integer promotions performed on each of operands. type of result of promoted left operand. if value of right operand negative or is greater or equal width of promoted left operand, behavior undefined.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -