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 09:01 (UTC)
bens_dad: (Default)
From: [personal profile] bens_dad
Hmm. My C appears to be too rusty to get the full subtlety of this but I think I agree with pm215 that in C you need to know whether you have a thing or a pointer to a thing. Unless you can use this consistently and everywhere, so that you never need to remember which, it is probably more dangerous to forget that you need to remember.

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.)

Date: 2007-11-21 12:04 (UTC)
ext_8103: (geek)
From: [identity profile] ewx.livejournal.com
I think you've confused it with the old struct passing behavior; AFAIK the array-to-pointer decay has always been that way.

Date: 2007-11-21 12:05 (UTC)
ext_8103: (geek)
From: [identity profile] ewx.livejournal.com
Oh, and all sorts of standard modern things don't work on pre-ANSI implementations: const and prototypes for instance. So suggesting that as even just an aesthetic reason is frankly rather silly.

Date: 2007-11-21 13:17 (UTC)
pm215: (Default)
From: [personal profile] pm215
Yeah, even gcc requires an ANSI C89 compiler these days. K&R non-prototyped function syntax is almost as dead as the "var =+ 4;" autoincrement syntax. (Aside: I wonder if the Green Hills C compiler still has the option switch to support =+ ...)

Date: 2007-11-21 14:09 (UTC)
bens_dad: (Default)
From: [personal profile] bens_dad
I was indeed thinking of that.

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:37
Powered by Dreamwidth Studios