Pointer magic
2007-11-20 21:42The following C type definition can be used for declaring local and global structure objects. You can initialize them as if they were bare structures, because C doesn't mind if you omit curly brackets in initializers (though gcc -Wall will complain). You can also use the typedef to declare function arguments, in which case the function will expect a pointer to the structure instead of a copy of it. Furthermore, when you use a variable declared with this typedef, it will be quietly converted into a pointer to the structure just as is expected by the function. This avoids a load of & operators and gives you a sort of poor-man's C++ pass-by-reference.
typedef struct mytype {
/* member declarations */
} mytype[1];
mytype var;
int func(mytype arg);
func(var);
ETA: it seems this trick is used by GMP (see the last paragraph of that page)
[Poll #1092168]
no subject
Date: 2007-11-20 22:35 (UTC)jmp_buf, isn't it? Hence why you don't have to specify the&when passing ajmp_bufto a function which is obviously going to modify it (such assetjmp).no subject
Date: 2007-11-20 22:49 (UTC)no subject
Date: 2007-11-20 23:00 (UTC)no subject
Date: 2007-11-20 23:21 (UTC)(Brought to you by the department of trolling comp.lang.c)
no subject
Date: 2007-11-20 23:21 (UTC)no subject
Date: 2007-11-21 05:20 (UTC)no subject
Date: 2007-11-21 09:01 (UTC)IIRC K&R C didn't allow you to pass arrays, so I'd be very uncomfortable about using this on a pre-ANSI C compiler.
(That isn't likely these days, so that is really an aesthetic complaint.)
no subject
Date: 2007-11-21 09:09 (UTC)Also if you want to define a more complex type with one of these things as its base type, it's hard to work out how. When I was working with GMP a while back I occasionally wanted to write a function which took a pointer to an array of
mpf_t; I managed it in the end by just adding or removing*s until the compiler stopped complaining, but I wouldn't say I understand the syntactic rules which make the right answer right and the wrong ones wrong. (And, just to put that in perspective, I do feel that I understand pretty much all the rest of the C declarator syntax, which I know isn't a statement all C programmers could make!)no subject
Date: 2007-11-21 10:19 (UTC)no subject
Date: 2007-11-21 10:54 (UTC)no subject
Date: 2007-11-21 12:04 (UTC)no subject
Date: 2007-11-21 12:05 (UTC)no subject
Date: 2007-11-21 13:17 (UTC)no subject
Date: 2007-11-21 14:09 (UTC)no subject
Date: 2008-01-04 09:32 (UTC)mytype another = varisn't valid C, so it doesn't make a copy.I've seen this trick used for va_list so that you could pass vararg lists to subroutines and have it work correctly, though the general form of this is not required by the standard.
I wouldn't really consider this a dark corner of C's array behaviour, it's simply one of those things you have to know before calling yourself a C programmer.