Article View: comp.std.c
Article #4993Re: Is it legal to add 0 to NULL? What about NULL < NULL?
From: Lawrence Kirby
Date: Sun, 07 Apr 1996 19:34
Date: Sun, 07 Apr 1996 19:34
54 lines
2352 bytes
2352 bytes
In article <ff1d.smail.smayo@tiac.net> smayo@tiac.net "Scott Mayo" writes:
>I ask because a standard trick for walking an array A of size S is:
>
>Thing *a = A;
>Thing *fence = a + S;
>for (; a < fence; ++a)
> /* use a */;
>
>but in my case, if S happens to be 0, a will start out NULL. This makes we
>worry about both the value of fence, and, if that works, the behaviour
>of (a < fence), which I hope is (NULL < NULL), which I hope the standard
>blesses as reliably false, but I have this feeling that it won't.
The standard says about addition 6.3.6:
"If both the pointer and the result point to elements of the same array
object, or one past the last element of the array object, the evaluation
shall not produce an overflow; otherwise the behaviour is undefined"
Unfortunately a null pointer doesn't point to an array object so we
invoke 'otherwise'.
Similarly comparison against a null pointer (even another one) is defined
for equality operators == and != but not for relational operators < <= > >=.
If S can't be negative you could use:
>for (; a != fence; ++a)
But if you've already tested for S being zero, it probably doesn't help.
As far as efficiency is concerned you could write:
if (S > 0) {
Thing *a = A;
Thing *fence = a + S;
do {
...
} while (++a < fence);
}
>I know I can use int i; for (i = 0; i < S; ++i) but I was
>hoping to avoid the extra math at array dereference time.
Any reasonable conpiler should be able to optimise that to a pointer as
appropriate. It might even do a better job at optimising that than with the
code above.
--
-----------------------------------------
Lawrence Kirby | fred@genesis.demon.co.uk
Wilts, England | 70734.126@compuserve.com
-----------------------------------------
Technical Details
Message-ID:
<828905693snz@genesis.demon.co.uk>Path:
arc1-ca.pugleaf.net!mail2news.demon.co.uk!genesis.demon.co.ukReferences:
<ff1d.smail.smayo@tiac.net>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!mail2news.demon.co.uk!genesis.demon.co.uk From: Lawrence Kirby <fred@genesis.demon.co.uk> Newsgroups: comp.std.c Subject: Re: Is it legal to add 0 to NULL? What about NULL < NULL? Date: Sun, 07 Apr 96 19:34:53 GMT Organization: none Message-ID: <828905693snz@genesis.demon.co.uk> References: <ff1d.smail.smayo@tiac.net> Reply-To: fred@genesis.demon.co.uk X-NNTP-Posting-Host: genesis.demon.co.uk X-Newsreader: Demon Internet Simple News v1.27 X-Mail2News-Path: genesis.demon.co.uk