shift count negative or too big, undefined behavior
Given:
Code:
typedef unsigned long long ulong_long_type ;
istream& istream::operator>>(
ulong_long_type& dest )
{
BGetter source( *this ) ;
ulong_long_type tmp = source.get() << 56 ;
tmp |= source.get() << 48 ;
tmp |= source.get() << 40 ;
tmp |= source.get() << 32 ;
tmp |= source.get() << 24 ;
tmp |= source.get() << 16 ;
tmp |= source.get() << 8 ;
tmp |= source.get() ;
return *this ;
}
During compilation I get warnings from Visual studio 2007 surrounding the left shift values 56, 48, 40 and 32, more specifically:
3>c:\sw_dev\msvc_2007-orcas\test\istream.h(158) : warning C4293: '<<' : shift count negative or too big, undefined behavior
3>c:\sw_dev\msvc_2007-orcas\test\istream.h(159) : warning C4293: '<<' : shift count negative or too big, undefined behavior
3>c:\sw_dev\msvc_2007-orcas\test\istream.h(160) : warning C4293: '<<' : shift count negative or too big, undefined behavior
3>c:\sw_dev\msvc_2007-orcas\test\istream.h(161) : warning C4293: '<<' : shift count negative or too big, undefined behavior
Of course I could ignore the warning but the claim of 'undefined behavior' is cause for concern. Thoughts.
Thanks in advance
Re: shift count negative or too big, undefined behavior
I dont think msvc understands long long, isn't that a gcc extension?
I think what its done is given you a 32 bit long when you wanted a 64 bit long. Fixable using __int64 but thats microsoft specific. Not 100% sure there is a portable way of declaring a 64 bit int.
Re: shift count negative or too big, undefined behavior
What is portable for 64bit int ?
Thanks.
Re: shift count negative or too big, undefined behavior
Quote:
Originally Posted by Peter_APIIT
What is portable for 64bit int ?
For C++ at the moment, nothing from the standard, though long long should be available in the next version of the C++ standard, and will probably be guaranteed to be at least 64 bits.
As such, you should use __int64 for Microsoft compilers.
Re: shift count negative or too big, undefined behavior
Re: shift count negative or too big, undefined behavior
In C99, it also supports int64_t for 64-bit int. So you may like to create a temporary typedef for int64_t so that when Visual C++ finally supports it, you will not have to change much of your code.
Code:
typedef __int64 int64_t;
Re: shift count negative or too big, undefined behavior
VS 2005 *does* support long long. That's not the problem. The problem is likely that source.get() is not returning a long long-----therefore, the shift operation is done on a 32-bit value. The program doesn't know or care that the result will be put into a long long after the shift is done.
Try this:
Code:
tmp |= static_cast<ulong_long_type>(source.get()) << 48 ;