Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

c - Can I name a variable with the same name as a typedef'd structure name?

Here is the structure declare code.

struct list_el {
    int val;
    struct list_el * next;
};

typedef struct list_el item;

And when I write a function like this, the compiler gives a error. It says cur undeclared before first use.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In this code:

bool delete(item* item)
{
    item *cur = NULL;

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.


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...