Why does C hate 2d arrays?

Peter da Silva peter at ficc.ferranti.com
Thu May 31 00:36:29 AEST 1990


In article <1376:May2720:09:0690 at stealth.acf.nyu.edu> brnstnd at stealth.acf.nyu.edu (Dan Bernstein) writes:
> How do you expect it to figure that out?

I can ask you the same question.

In my case, it's just an optimisation. In your case, it's needed to even
generate legal code. Think of the possibilities for hidden bugs!

> And once m and n do change,
> where do you think it's going to store the original values?

Up to the compiler writer. There are a number of possibilities. It's like
structure passing/returning.

> Why not let the programmer have control over those values?

Why not let the programmer have control over these variables?

> 
> > struct _point { int x, y };
> > foo(box) struct point box[2]; {
> > 	char tmp[box[1].x - box[0].x][box[1].y - box[0].y];
> > 	bar(box, tmp); print(box, tmp); }
> > How do you guarantee that box is constant? In general, you can't.

> Q requires that array dimensions be const (i.e., unvarying within their
> scope, lifetime, whatever). Given box declared const, the answer is
> ``yes, you can.'' const filters down through function invocations: if
> bar were to change box, then it couldn't declare box constant in the
> function declaration, so bar(box,tmp) (rather, bar(&box,&tmp), because Q
> treats arrays differently) wouldn't be valid.

> This all makes perfect sense. What are you objecting to?

Now the compiler has to mark all the variables in those expressions const
as well? Or require that?

What if "box" is an extern?

What if the expression evaluation requires a function call? (say, using
object oriented techniques.

There are only two alternatives that I see that make sense.

The compiler squirrels the dimensions away.

The dimensions are const auto integer variables, autoinitialised before
the declaration of the array if they're not formal parameters.

> Why don't you give an example where requiring the dimensions to be
> const restricts the programmer? I see it as more flexible.

You can't use a function or an external variable in deriving the
dimensions. None of the variables involved can be aliased.
-- 
`-_-' Peter da Silva. +1 713 274 5180.  <peter at ficc.ferranti.com>
 'U`  Have you hugged your wolf today?  <peter at sugar.hackercorp.com>
@FIN  Dirty words: Zhghnyyl erphefvir vayvar shapgvbaf.



More information about the Comp.lang.c mailing list