shorthand typedef pointer to a constant struct

谁说胖子不能爱 提交于 2019-12-12 09:49:33

问题


Declaring a struct with typedef

typedef struct some_struct {
int someValue;
} *pSomeStruct;

and then passing it as a parameter 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 )

回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6609422/shorthand-typedef-pointer-to-a-constant-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!