Re: CFO: Why C?

From: Måns Rullgård (
Date: 09/10/03

Date: Wed, 10 Sep 2003 11:15:46 +0200 (VBDis) writes:

>>It is often said that Java has no pointers. This is easily proven
>>wrong. Just look up NullPointerException. Renaming pointers to
>>references doesn't change anything fundamental.
> The difference between pointers and references is more than only a
> rename. At least in C++ references cannot be NULL, that's a
> significant difference from unmanaged pointers. References also
> cannot be modified, by pointer arithmetic. What remains is a check
> for possibly uninitialized variables.

I explicitly mentioned Java references. C++ references are something
quite different.

>>It's true that if pointers are not used, certain errors can't happen.
>>However, it's not only errors that are banished by this. A lot of
>>nice functionality is lost as well.
> Can you give concrete examples?

Pointer arithmetic comes to mind. My old example of extracting an
integer from a byte array is another example.

>>Doing things perfectly safely is impossible without runtime checks.
> Agreed, when dynamic arrays come into play. Do you know of other situations?

Any use of dynamically allocated memory (not only arrays), or indexing
static arrays with a variable index could result in illegal accesses.

>>Runtime checks always take some extra time.
> Sometimes appropriate runtime checks can even save time! Consider a
> loop over an array, where in traditional code often a pointer as
> well as an index (loop variable) is incremented or decremented and
> tested for every iteration. With indexed access to the array the
> compiler will almost use the same procedure, with an implicit
> pointer, but it can create faster code for the loop test (LOOPNE or
> similar, for the assembly freaks ;-)

Well, that ain't the way I code. Even if I did, the compiler would
most likely eliminate one of the variables. Have you ever looked at
the output of an optimizing C compiler.

> In another case, when counted instead of zero terminated strings are
> used, a test for the trailing null byte is obsolete, since the
> length of the string is known before entering the loop, and can
> immediatley be used as the loop count. Similarly NULL pointers
> deserve no checking code at all, when references are used.

What about the common use of NULL pointers to signify an error, or
default value?

>>Even with the checks,
>>there is nothing you can do but abort, when there is a violation.
> Compile time checks reduce the amount of remaining runtime checks. I just can
> imagine only two possible cases, but perhaps you find more:
> - index bounds violation
> - out of memory during allocation

Use of uninitialized memory. This is more or less impossible to do
efficiently, and totally impossible at compile time. The solution is
a debugger, like valgrind. Memory leaks are also difficult find
without some overhead. Don't say garbage collector. I don't like

Måns Rullgård