Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does zlib make an effort to compute only a positive pointer difference?

Tags:

c

zlib

In zlib 1.2.7, file inffast.c, line 320, there is a statement that I do not understand:

strm->avail_out = (unsigned)(out < end ?
                             257 + (end - out) : 257 - (out - end));

Variables end and out are two pointers into the output buffer. This statement makes an effort to compute end - out when end > out and out - end when out >= end, but I do not see why it might want to do that. It seems to me that the end result is the same, that is, the line might as well have been written:

strm->avail_out = 257 + (end - out);

The difference of two pointers has a signed integral type, ptrdiff_t (C99 6.5.6:9), and 257 has type int. The addition takes place in the type of higher rank between these two, and I do not see what the ternary operator could possibly be guarding against.

like image 664
Pascal Cuoq Avatar asked Jan 17 '13 07:01

Pascal Cuoq


1 Answers

Your observation is correct for C99 as well as C89/C90.

That line of code was written ten years ago. At this point my memory permits me only to be able to claim paranoia as the excuse. Apparently I was concerned that in some compilers the result of subtracting two pointers might be unsigned. I do not recall the origin of that concern, or if it had any basis at all.

As for the change history, that line of code was born from the brow of Zeus as you see it today. It has not been changed since it was written.

like image 165
Mark Adler Avatar answered Nov 03 '22 09:11

Mark Adler