2

Are the following expressions well defined?

  • (int *)0 + 0
  • (int *)0 - (int *)0

Note: Is it allowed to add a zero to a null pointer? is the same question for C++.

Lundin
  • 195,001
  • 40
  • 254
  • 396
David Stone
  • 26,872
  • 14
  • 68
  • 84
  • @EugeneSh. I don't think the accepted answer to that question covers the specific case of adding zero. – Christian Gibbons Apr 27 '21 at 21:55
  • @ChristianGibbons Doesn't matter how much you're adding. A NULL pointer doesn't point to an object, so you can't do arithmetic on it. – dbush Apr 27 '21 at 21:58
  • @dbush I don't disagree, but I'd look for a specific reference to agree with that. I believe I've found how the wording of the standard makes that the case and will be writing an answer that shows it. – Christian Gibbons Apr 27 '21 at 22:01
  • 1
    @dbush: Allowing code to treat null as a pointer to an allocation of size zero makes it possible to avoid having to write a lot of useless corner-case code that for which optimizers would generally have to generate useless machine code. – supercat Apr 27 '21 at 22:01
  • @ChristianGibbons: The C Standard was never intended to fully describe all of the constructs that should be usefully processed by all compilers for remotely commonplace platforms. There has never been any reason for non-garbage-quality general-purpose compilers not to usefully process many useful constructs beyond those mandated by the Standard. – supercat Apr 27 '21 at 22:03
  • @supercat That may be true, but when language-lawyering (as was tagged in this question), it doesn't hurt to first try to pick apart the standard and see if it does adequately describe the construct in question. – Christian Gibbons Apr 27 '21 at 22:21
  • @ChristianGibbons: The only reason "language-lawyer C" is a remotely usable language is that language lawyers pretend the Standard defines things it actually doesn't. Under a sufficiently obtuse, but nonetheless literally correct, reading of the Standard, roughly 0% of non-contrived programs would manage to avoid violating N1570 6.5p7, which states that nothing can modify an object except an lvalue of the proper type. An assignment expression like `x=3;` isn't an lvalue, and using the ordinary meanings of English language preposition "by", the stored value associated with the object... – supercat Apr 28 '21 at 06:07
  • ...at address `&x` may be modified *using* the lvalue `x`, but isn't modified *by* the lvalue itself. Of course, no compiler whose authors aren't being deliberately obtuse would require that programmers write `memcpy(&x, &(int){3}, sizeof x);` rather than `x=3;`, but no compiler whose authors aren't being deliberately obtuse would be more interested in whether support for various constructs was mandated by the Standard or necessary to run their users' programs. – supercat Apr 28 '21 at 06:11

0 Answers0