0
printf("%td",i-j); when `*i > *j`  the type of both `i` and `j` is `int`

if we take, i = &a; j = &b;

we would get a normal integer difference, i.e. 42-23 = 19

But if we use this code,

printf("%td\n",i- j);   if `*i < *j`

with the same scenario, the answer is an unrelated integer. Why?

coderredoc
  • 27
  • 4

2 Answers2

1

The behaviour of your code is undefined.

Pointer arithmetic, including the evaluation of the difference between two pointers, is only defined within arrays (one past the end of the array is included and for this purpose an object that is not an element of an array is considered to be a single element array).

Your format specifier %td is the correct one.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Per 6.5.6 Additive operators, paragraph 9 of the C standard (emphasis mine):

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object ...

Therefore, your results are undefined behavior.

Community
  • 1
  • 1
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
  • 1
    Do mention that "for this purpose a scalar is considered to be a single element array", or something on those lines anyway. – Bathsheba Feb 05 '18 at 16:00
  • 1
    @Bathsheba Paragraph 7 of 6.5.6? "For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."? I'm not seeing how that applies here. – Andrew Henle Feb 05 '18 at 16:28
  • That's the one. It's just that you've answered on the "standard route", and it's nice to have such answers comprehensive. – Bathsheba Feb 05 '18 at 16:30