If the warning is on the return
, in:
int istrlen(char *s)
{
...
return p - s;
}
Then your compiler is being helpful... in this case, gcc will generate a warning if you ask for -Wconversion
, because...
...the sum p - s
is defined (C99 6.5.6), where both are pointers (to elements of the same array object, or to one past the last element of the same array object), to give a result of type ptrdiff_t
-- which is a signed integer. Now, on a typical 64-bit processor your ptrdiff_t
will be a 64-bit signed integer, and your int
is a 32-bit signed integer. So, your compiler may be warning you that the conversion down from 64-bit to 32-bit signed integer, there could be an overflow.
You can write:
return (int)(p - s) ;
to take responsibility for this, and the compiler will shrug and get on with its life.
[I'm slightly surprised that the warning is not given with straightforward -Wall
... so this may not be the warning the question refers to.]
My second edition K&R is essentially C89, and also describes ptrdiff_t
and its pal size_t
. I suspect the fragment of code you are looking at comes from a kinder, gentler age when int
and ptrdiff_t
were interchangeable (32-bit integers) -- or compilers were less keen to suggest that the programmer may not know what they are doing. (Mind you, in 1989 a string longer than 2,147,483,647 characters was seriously unlikely !)
The other place where the compiler may be being helpful is at the:
printf("%d\n", (sp+7) - s);
Where, again, the result of the subtraction is ptrdiff_t
, but the %d
expects an int
. This is a more serious problem, because the %d
only knows how to eat an int
, and may go wrong eating an int
, especially where there are more arguments following it.