shorthand typedef pointer to a constant struct
Declaring a struct with typedef
typedef struct some_struct {
int someValue;
} *pSomeStruct;
and then passing it as a parame开发者_运维技巧ter to some function with const declaration, implying 'const some_struct * var'
void someFunction1( const pSomeStruct var )
turns out to become
some_struct * const var
This is also stated in Section 6.7.5.1 of the ISO C standard which states that 'const' in this case applies to the pointer and not to the data to which it points.
So the question is - is there a way to declare a pointer to a const struct in a shorthanded notation with typedef, or there must always be a special separate declaration for it:
typedef const struct some_struct *pcSomeStruct;
void someFunction2( pcSomeStruct var )
Basically, do not typedef pointers :)
typedef struct some_struct {} some_struct;
void some_function1(some_struct *var);
void some_function2(const some_struct *var);
void some_function3(some_struct *const var);
void some_function4(const some_struct *const var);
Or, don't typedef at all :D
struct some_struct {};
void some_function1(struct some_struct *var);
void some_function2(const struct some_struct *var);
void some_function3(struct some_struct *const var);
void some_function4(const struct some_struct *const var);
Those are valid, too:
typedef struct some_struct {
int someValue;
} const * pSomeStruct;
typedef struct some_struct {
int someValue;
} const * const pSomeStruct;
This style is not used widely in C++, though. Rather:
struct some_struct {
int someValue;
};
struct some_struct {
int someValue;
};
and then do seperate typedefs. But then, that's not widely used as well. Many other C++ programmers and me would rather declare your functions like void foo (some_struct const * const)
or similar, apart from the usual reasons against pointers.
As far as my understanding of C type system goes, you should not. First typedef declares type that reas as "pointer to the struct". Applying const to it logically creates "const pointer to the struct". Injecting const'ness to the struct itself would require changing type itself and, so it goes, retypedef'ing. AFAIK, type composition in C is incremental and you can only make new types by applying modifiers to existing ones, not injecting.
Typedef of a pointer in not a good style anyway.
精彩评论