shorthand typedef pointer to a constant struct

▼魔方 西西 提交于 2019-12-06 02:30:35

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.

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