Type of result of pointer arithmetic

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

int main( void ) {
int foo[10], *bar=foo, *baz=foo+1;
int quux=baz-bar;
return 0;
}

Is the type of quux (that is, int) strictly correct? Or is there a
type similar to size_t that is more appropriate for the difference of
two pointers?
 
J

Jordan Abel

int main( void ) {
int foo[10], *bar=foo, *baz=foo+1;
int quux=baz-bar;
return 0;
}

Is the type of quux (that is, int) strictly correct? Or is there a
type similar to size_t that is more appropriate for the difference of
two pointers?

ptrdiff_t
 
K

Keith Thompson

Christopher Benson-Manica said:
int main( void ) {
int foo[10], *bar=foo, *baz=foo+1;
int quux=baz-bar;
return 0;
}

Is the type of quux (that is, int) strictly correct? Or is there a
type similar to size_t that is more appropriate for the difference of
two pointers?

ptrdiff_t is correct (as Jordan Abel has already pointed out). On the
other hand, that doesn't mean the code above is wrong. As long as you
know the result won't exceed 32767, there's nothing wrong with
assigning it to an int and taking advantage of the implicit
conversion.

But declaring quux as a prtdiff_t is more robust.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,916
Members
47,458
Latest member
Chris#

Latest Threads

Top