Re: Expression evaluation using __int64
- From: "Carl Daniel [VC++ MVP]" <cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx>
- Date: Mon, 17 Sep 2007 23:10:33 -0700
Jeff Bean wrote:
I need to compute a 64 bit file offset which will get passed to the
_lseeki64 function.
The inputs to the offset calculation are all unsigned shorts or
unsigned longs. For example:
unsigned short page_size;
unsigned long page_index;
unsigned long page_offset;
__int64 file_offset;
file_offset = (page_size * page_index) + page_offset;
I think that the above expression is subject to integer overflow, but
I am not clear on how to ensure that the intermediate values in the
expression are calculated using 64 bits. The topic on "Integral
Promotions" in the VC++ Language Reference states the following:
"C++ promotions are "value-preserving." That is, the value after the
promotion is guaranteed to be the same as the value before the
promotion. In value-preserving promotions, objects of shorter
integral types (such as bit fields or objects of type char) are
promoted to type int if int can represent the full range of the
original type. If int cannot represent the full range of values, then
the object is promoted to type unsigned int. Although this strategy
is the same as that used by ANSI C, value-preserving conversions do
not preserve the "signedness" of the object."
The above paragraph is silent on what happens if one of the values is
longer than an int. If I change the above expression to:
file_offset = (page_size * (__int64)page_index) + page_offset;
does that guarantee that the intermediate value (page_size *
(__int64)page) will be evaluated using 64 bits? Are all intermediate
values involving 64 bit integers also 64 bit integers?
Yes. Casting either of the multiplicands as you've shown will guarantee
that the entire expression is evaluated as 64 bit integers.
-cd
.
- Follow-Ups:
- Re: Expression evaluation using __int64
- From: Jeff Bean
- Re: Expression evaluation using __int64
- From: Doug Harrison [MVP]
- Re: Expression evaluation using __int64
- References:
- Expression evaluation using __int64
- From: Jeff Bean
- Expression evaluation using __int64
- Prev by Date: Re: C++/CLI control null exceptions
- Next by Date: Word automation using vc 2005
- Previous by thread: Expression evaluation using __int64
- Next by thread: Re: Expression evaluation using __int64
- Index(es):
Relevant Pages
|