我能说出具有相同的名称为typedef定义结构名称的变量? [英] Can I name a variable with the same name as a typedef'd structure name?
问题描述
下面是结构宣告code。
Here is the structure declare code.
struct list_el {
int val;
struct list_el * next;
};
typedef struct list_el item;
当我写这样一个函数,编译器给出了错误。它说 CUR未申报首次使用前
。
bool delete(item* item)
{
assert(item != NULL);
item* cur = NULL;
cur = head;
item* prev = NULL;
while (cur) {
if (cur == item) {
if (prev == NULL) {
head = item->next;
} else {
prev->next = item->next;
}
free(item);
return true;
}
prev = cur;
cur = cur->next;
}
return false;
}
在我抬头看的参考,它说,的typedef
和出刚刚有点像的#define
。它只是使在编译时替换。是的原因code不能编译?
After I look up the reference, it says the typedef
works out just a bit like #define
. It simply makes a substitution at compile time. Is that the reason the code can't be compiled?
推荐答案
在此code:
bool delete(item* item)
{
item *cur = NULL;
在项目
在第三行被当作变量项目
(参数传递给名功能),而不是类型。因此,第三行看起来好像它开始作为一个前pression倍增项目
由不确定的变量 CUR
,这导致的问题;恩pression其余也是伪造的。
the item
in the third line is taken to be the name of the variable item
(the parameter to the function), and not the type. Consequently, the third line looks as if it starts out as an expression that multiplies item
by the undefined variable cur
, which leads to problems; the rest of the expression is also bogus.
如果这不是你想要的,不要为一个类型和一个变量使用相同的名称。你会迷惑别人,即使你不要混淆自己和编译器。
If this isn't what you want, don't use the same name for a type and a variable. You'll confuse other people even if you don't confuse yourself and the compiler.
无论引用消息人士称,的typedef
和的#define
是相同应该从你的列表中删除引用的现在的!如果它不能区分这样两个根本不同的结构,这是危险的,因为你不会知道当它被误导你(但是这是一种情况是误导你)。
Whichever reference source said that typedef
and #define
are 'the same' should be dropped from your list of references now! If it can't differentiate two such fundamentally different constructs, it is dangerous because you won't know when it is misleading you (but this is one case where it is misleading you).
这篇关于我能说出具有相同的名称为typedef定义结构名称的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!