问题描述
考虑以下C代码:
typedef char * MYCHAR;
MYCHAR x;
我的理解是,结果将是x是"char"类型的指针.但是,如果x的声明发生在远离typedef命令的地方,那么代码的人工阅读者将不会立即知道x是一个指针.或者,可以使用
My understanding is that the result would be that x is a pointer of type "char". However, if the declaration of x were to occur far away from the typedef command, a human reader of the code would not immediately know that x is a pointer. Alternatively, one could use
typedef char MYCHAR;
MYCHAR *x;
哪个被认为是更好的形式?这不仅仅是样式问题吗?
Which is considered to be better form? Is this more than a matter of style?
推荐答案
仅在结果类型的指针性质不重要的情况下,才使用指针typedef.例如,当有人想声明一种不透明的句柄"类型时,指针typedef是合理的,该类型恰好实现为指针,但不应被用户用作指针.
I would use pointer typedefs only in situations when the pointer nature of the resultant type is of no significance. For example, pointer typedef is justified when one wants to declare an opaque "handle" type which just happens to be implemented as a pointer, but is not supposed to be usable as a pointer by the user.
typedef struct HashTableImpl *HashTable;
/* 'struct HashTableImpl' is (or is supposed to be) an opaque type */
在上面的示例中,HashTable
是哈希表的句柄".用户最初会从例如CreateHashTable
函数接收该句柄,并将其传递给例如HashInsert
函数等.用户不应该关心(甚至不知道)HashTable
是一个指针.
In the above example, HashTable
is a "handle" for a hash table. The user will receive that handle initially from, say, CreateHashTable
function and pass it to, say, HashInsert
function and such. The user is not supposed to care (or even know) that HashTable
is a pointer.
但是在用户应该理解类型实际上是一个指针并且可用作指针的情况下,指针typedef会极大地混淆代码.我会避免他们.显式声明指针可使代码更具可读性.
But in cases when the user is supposed to understand that the type is actually a pointer and is usable as a pointer, pointer typedefs are significantly obfuscating the code. I would avoid them. Declaring pointers explicitly makes code more readable.
有趣的是,C标准库避免了此类指针typedef.例如,FILE
显然打算用作不透明类型,这意味着库可以将其定义为typedef FILE <some pointer type>
,而不是让我们一直使用FILE *
.但是出于某种原因,他们决定不这么做.
It is interesting to note that C standard library avoids such pointer typedefs. For example, FILE
is obviously intended to be used as an opaque type, which means that the library could have defined it as typedef FILE <some pointer type>
instead of making us to use FILE *
all the time. But for some reason they decided not to.
这篇关于在C语言中,将typedef用作指针是一种好形式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!