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 05:20 (UTC)
pm215: (Default)
From: [personal profile] pm215
I don't like this for the same reason I don't like C++'s pass-by-reference -- it hides the distinction between passing a thing and passing a pointer to a thing, which IMHO is a fundamental difference that you really want to know about.

Date: 2007-11-21 09:09 (UTC)
simont: A picture of me in 2016 (Default)
From: [personal profile] simont
I agree with this.

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

Date: 2007-11-21 10:19 (UTC)
From: [identity profile] gareth-rees.livejournal.com
If in doubt, I suggest using something like this:
typedef mpf_t array_of_unknown_size_of_mpf_t[];
typedef array_of_unknown_size_of_mpf_t *pointer_to_array_of_unknown_size_of_mpf_t;

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