General Category > Ideas

Array types

(1/2) > >>

bas:
I recently read
http://www.drdobbs.com/architecture-and-design/cs-biggest-mistake/228701625
where the author states that the (one of) the biggest mistakes made in C was
converting an array to a pointer when calling a function, so (C-code)

--- Code: ---int array[4];
int* ip = &array[0];
myfunction(array);
myfunction(ip);

--- End code ---
the two calls are equal. One idea would be to make this distinction. One limit would be
that the array would be a known size (in function prototype), eg (C2 code)

--- Code: ---func void setMacnr(char[4] macnr) { .. }

--- End code ---
A function that would take a variable sized array (like string functions) would still require a pointer and a size
argument.

kyle:
Thanks for the link.  Walter Bright makes a good case for this. 

Passing "fat pointers," as Walter mentions, is one way to solve this.   Go uses them to pass values and vtables. 

Not only are arrays and pointers conflated, but now you have "magic" happening in that arrays are treated as pass-by-reference whereas other values must have "*/&" to show that they are passed by reference.  I actually find this aspect of the automatic conversion to be more problematic.  If I pass something by value, I expect that there is nothing that will alter the values in the caller.  If I pass something by reference, I accept that the callee could modify data in the caller.

Pass by value:

--- Code: ---int foo(int p);

int x;

foo(x);

--- End code ---


Pass by reference:

--- Code: ---int foo(int *p);

int x;

foo(&x);

--- End code ---


Pass by value:

--- Code: ---int foo(struct bar p);

struct bar x;

foo(x);

--- End code ---

Pass by reference:

--- Code: ---int foo(int p[]);

int x[2];

foo(x);

--- End code ---

Huh?  This really violates the principle of least surprise.

If I pass a struct without explicitly getting its address, the struct is copied.  Arrays should be too.  Are there other things that are treated specially too?

I have programmed in C for so long that I never really thought too much about this.  Java does the same thing with primitive types vs. objects.

Good find!

Best,
Kyle

norm:
I found this proposal by John Nagel on Lambda The Ultimate : http://lambda-the-ultimate.org/node/4573

The idea is to tie together parameters in a function declaration so the compiler can see that one of the parameters is the length of the array in the other parameter. Look at the "n" in this example he gives:

    int read(int fd, char (&buf)[n], size_t n); 

Even if this proposal isn't appropriate, maybe the reaction and discussion is informative.


kyle:
Oooh!  Thanks for the link!

Interesting proposal. 

bas:
I'm currently playing with the idea of forbidding passing array types like (int[] a) as function argument. A developer would have to use (int* a). In the function body he/she could do a[4].

Anyone have a any other ideas on this?

Navigation

[0] Message Index

[#] Next page

Go to full version