C array follies 1

Guy Harris guy at sun.uucp
Thu Sep 12 19:19:55 AEST 1985


> I am suggesting that the latter notion is a good idea.  In particular,
> the formal declaration
>         int x[3];
> should make sizeof(x) == (sizeof(int) * 3).

An alternative is simply to forbid such a formal declaration.

	foo(x)
	int *x;
	{
		x++;
	}

would, if "x" pointed to the "i"th element of an array of "int"s, cause "x"
to point to the "i+1"st element of that array.

	foo(x)
	int x[3];
	{
		x++;
	}

would cause great confusion, since

	foo()
	{
		int x[3];

		x++;
	}

is illegal.

C doesn't permit you to pass arrays by value, so I think

	foo(x)
	int x[3];
	{
		...

is meaningless.  If C permitted you to take the address of an array other
than a subarray,

	foo(x)
	int (*x)[3];
	{
		...

might be meaningful and useful (it says that "foo" takes a pointer to an
array with 3 "int" elements - not 4, not 2, but 3 and only 3).  However, you
can't take the address of such an array, so

	bar()
	{
		int y[3];

		foo(&y);
	}

is illegal.

C's "declaration syntax == usage syntax" breaks down when it comes to arrays.

	int a[3];

	a[1] = 1;
	*(a + 2) = 2;

is legal, and would also be legal if "a" were declared as

	int *a;

However, the code, while still legal C, would mean something very different
in the second form.

Since a declaration of a formal argument is, not surprisingly, a
declaration, and since the declarations "int a[];" and "int *a;" are
inequivalent if "a" is not a formal argument, I don't think array
declarations and pointer declarations should be equivalent for formal
arguments.  Since it is nonsensical to declare an array formal, it should be
made illegal or, at least, deprecated - too much code uses "int a[];" as a
synonym for "int *a;" when declaring a formal to simply forbid it.

	Guy Harris



More information about the Comp.lang.c mailing list