fanf: (Default)
[personal profile] fanf

The 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]

Date: 2007-11-21 10:54 (UTC)
gerald_duck: (duck and computer)
From: [personal profile] gerald_duck
I don't like some of the darker corners of C's array behaviour anyway, and this exhibits them in a place where you're not expecting them. Particularly, while func(var) passes by reference, mytype another = var; makes a copy. C++'s references have their faults, but argument binding behaviour differing from assignment behaviour isn't one of them.

Date: 2008-01-04 09:32 (UTC)
From: [identity profile] drj11.livejournal.com
mytype another = var isn'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.

December 2025

S M T W T F S
 123456
78910111213
14151617181920
21222324 252627
28293031   

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated 2025-12-26 21:32
Powered by Dreamwidth Studios