Liste des Groupes | Revenir à cl c |
bart <bc@freeuk.com> writes:Apparently so has C! At least, there is enough of a mish-mash between by-value, by-reference, and explicit pointers, that it provides most of the benefits that true by-reference gives.On 10/07/2024 15:54, Janis Papanagnou wrote:Here's a modified version of your program:Values passed (including values of pointers [used for arrays]) are>
handled (in the functions) as copies and cannot change the original
entities (values or dereferenced objects) in the calling environment.
To make it possible to change entities in the calling environment
in "C" you have to implement the necessary indirection by pointers.
>
You don't have to do anything at all:
>
#include <stdio.h>
typedef unsigned char byte;
typedef byte vector[4];
>
void F(vector a) {
a[0]+=3;
a[1]+=3;
}
>
int main(void) {
vector v = {10,20,30,40};
>
printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]); // 10 20 30 40
F(v);
printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]); // 13 23 30 49
}
>
Here it looks superficially as though 'v' is passed by value (and it
is of a size that the ABI /would/ pass by value), yet F changes its
caller's data, perhaps unintentionally.
```
#include <stdio.h>
typedef unsigned char byte;
typedef byte vector[4];
void F(vector a) {
a[0]+=3;
a[1]+=3;
printf("In F\n");
printf(" a is of type %s\n",
_Generic(a, vector: "vector", byte*: "byte*"));
printf(" a = %p\n", (void*)a);
printf(" a+1 = %p\n", (void*)(a+1));
printf(" sizeof a = %zu\n", sizeof a);
printf(" *a = %d\n", *a);
}
int main(void) {
vector v = {10,20,30,40};
printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]); // 10 20 30 40
F(v);
printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]); // 13 23 30 49
}
```
The output is:
```
10 20 30 40
In F
a is of type byte*
a = 0x7ffdf0158d44
a+1 = 0x7ffdf0158d45
sizeof a = 8
*a = 13
13 23 30 40
```
(The pointer values will vary.)
Make a copy of the array data if you need to change a local copy, orYour insistence is amazing./I/ am amazed at everyone's insistence that there is nothing
remarkable about this, and that it is nothing at all like
pass-by-reference.
>
So, how do I write F in C so that the caller's data is unchanged?
define it as const so the function can't change it, or wrap the array in
a struct.
Sure, true pass-by-reference has some extra properties, but if ISo your language has pass-by-reference. Great. I'm sure we're all very
wanted to duplicate the behaviour of the above in my language, I have
to use pass-by-reference.
happy for you.
Which is more unsafe out these:In C you get that behaviour anyway (possibly to the surprise of many),Yes.
in a language which only has pass-by-value, and without needing
explicit pointers.
That really is remarkable. And not unsafe at all!Yes, it's remarkable. Yes, it can be unsafe.
It's particularly unsafe for someone who doesn't understand it, perhaps
because they took your advice.
Les messages affichés proviennent d'usenet.