Pass by Reference in C
When reading
setjmp.h
I figured out a nice trick used by glibc hackers to implement pass-by-reference'd data types. It was like Wow! Cool! Beautiful! Automatic memory allocation with no reference operator when passing to functions. This has been indeed part of the design of C and exactly why array types were added to C, yet I never figured out arrays can be used to implement opaque types that are passed by reference.
#include <stdio.h>
typedef struct __dummy_tag {
int x;
} the_type[1];
void
setter(the_type i, int v)
{
i->x = v;
}
int
getter(the_type i)
{
return i->x;
}
int
main(void)
{
the_type v;
setter (v, 10);
printf ("%d\n", getter (v));
setter (v, 20);
printf ("%d\n", getter (v));
return 0;
}
You learn new things everyday...
Update: Apparently
blogger has !@#$ed up my post. Kindly read the code syntax-highlighted and cutely-indented in my blog.
Update2: Originally I had planet blamed instead of blogger in the previous update. Giving up after a few tries to do overstrike on planet, I simply replaced it with blogger.