Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Why is C not consistent

Name: Anonymous 2012-05-10 1:43

Take the following two declarations "int arr[3]" and "int *ptr".

Both require different storage, but in usage both are identical. This behaviour  is known, and it is not the consistency I am talking about.

Take the following two declarations:

void funcarr(int a, int arr[3], int c)
{ printf("%d\n", &c-&a); }

void funcptr(int a, int *ptr, int c)
{ printf("%d\n", &c-&a); }

For funcarr, all three arguments are intended to be call by value. So I would expect the stack to contain
a,arr[0],arr[1],arr[2],c
but it does not. The stack contains
a,&arr[0],c

This is *NOT* consistent, and gives a false impression that the elements of arr[] will not change within the lifetime of the function.

Who failed, so I knows whose ass to kick.

Name: Anonymous 2012-05-12 20:00

>>18
This is pretty much the correct answer, although it's due to backwards compatibility with B, not BCPL.

B was the predecessor to C and it didn't have record types (or any types other than ints and arrays.) When you declared an array, e.g. a[5], the compiler created space for six ints: five for the array contents, and one as a pointer to the start of the array. The identifier for an array represented a real pointer in memory. You could actually re-seat the internal storage of arrays in B:

a[5];
b[5];
b = a;


So it made sense that arrays are passed to a functions by reference, because you're not passing the array contents; you're passing the value of the array pointer itself, same as what happens when you assign to an array.

The problem is once they introduced structs, there was no obvious way to initialize the pointer to an array in a struct.

struct foo {
  a[5];
};


If this actually contains six ints, one of which is a pointer to the array, where do we set it? If I malloc() some memory and cast it to a struct foo*, that pointer doesn't get set. So they changed it: the identifier for an array when used in an expression just generates the pointer to the array on the fly. It could no longer be assigned to (because it no longer has storage), but to remain backwards compatible with the existing body of B code, it would still be passed as pointer when used as a function argument.

http://cm.bell-labs.com/who/dmr/chist.html

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List