c programming style - READ THIS

Guy Harris guy at sun.uucp
Thu Jul 18 15:20:43 AEST 1985


> They came up with a language called DASL (*), based very strongly on C
> which actually perverted the meaning of arithmetic in such a way that 
> "argv = argv + n" ACTUALLY MEANT "argv = argv + n*sizeof(argv *)" !!

Well, what do you mean by "actually meant"?  The C operation of adding an
integer to a pointer does ***!!NOT!!*** mean "take the integer value which
the same bit pattern as the pointer, add the other integer value to it, and
stuff the bit pattern for the resulting value back into the pointer."  It
means (as has been pointed out several times to the readers of this
newsgroup who somehow have decided otherwise) that if the pointer is
considered to be pointing to the Nth element of an array of items of the
type given by dereferencing the pointer, it is to point to the N+Mth item,
where M is the integer value added to the pointer.  If your phrase "actually
meant" means "performs the specified operation on the underlying bit
patterns", "argv = argv + n" *does* "actually mean" (in that sense) "argv +
n*sizeof(*argv)".

However, one would hope that the C community has stopped thinking in terms
of the underlying bit patterns by now, and actually has a reasonable
abstract model of what C programs do.  Unfortunately, I'm afraid that's not
the case.  It may be that post-C programming languages will have to avoid
defining the result of adding an integer to a pointer and various other C
features that seem to cause a fair bit of confusion to some (such as array
names standing for a constant pointer to the first element of the array).

Now the READ THIS part:

	1) The only operation in C that adds an integer to the integer
	   with the same bit pattern as a given pointer and produces a
	   pointer value with the same bit pattern as the result is

	   (pointer_type) ((int)pointer + integer_value)

	2) "++a" and "a += 1" are completely equivalent expressions.
	   "a++" is almost equivalent; it yields the value before 1 is
	   added to "a", rather than the value after "1" is added.

and, while I'm at it,

	3) A pointer to "foo" and an array of "foo"s are not equivalent.
	   The declarations

		foo *p;

	   and

		foo p[666];

	   are not in any way, shape, or form equivalent - with one exception
	   (an unfortunate one, considering that every six months or so
	   somebody in net.lang.c asks why their program doesn't work when
	   they use the first declaration in one module, the second
	   declaration in another, and link the two modules together).  The
	   second style of declaration is interpreted as being the first
	   style when an argument to a procedure is declared.

Please read, digest, and remember.  Thank you.

	RTFM,
	Guy Harris



More information about the Comp.lang.c mailing list