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

后端 未结 5 1039
北荒
北荒 2020-12-20 14:14

Here is the structure declare code.

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

typedef struct list_el item;

And when I

相关标签:
5条回答
  • 2020-12-20 14:58

    you should use -Wshadow when you compile you code. Then, gcc will tell you where you are wrong. :-) like follows:
    declaration of ‘item’ shadows a global declaration [-Wshadow]

    0 讨论(0)
  • 2020-12-20 15:01

    typedef is not completely same as #define

    Here is the difference by example:

    #define cptr1 char*
    
    typedef char* cptr2;
    

    In code:

               int main()
                {
                 cptr1 c1,c2; // first case : 
            // here c1 will be pointer to char but c2 is only char as cptr 
       // is directly replaced by char* by preprocessor
                cptr2 c3,c4; // second case :
          // here c3 and c4 both are pointers to char 
                }
    
    0 讨论(0)
  • 2020-12-20 15:02

    Jonathan Leffler answered you your question.

    I just want to add: if you write your code in c++, you don't need to typedef, so you can implement your list just like this:

    struct list_el {
        int val;
        list_el *next;
    };
    
    bool delete_element(list_el *item)
    {
        list_el *cur = NULL;
        ...
    }
    
    0 讨论(0)
  • 2020-12-20 15:04

    A typedef is just a new name for an already existing type. defines are handled by the preprocessor while typedefs are handled by the C compiler itself. [copied from this link]

    check this question: Are typedef and #define the same in c?

    0 讨论(0)
  • 2020-12-20 15:06

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

    0 讨论(0)
提交回复
热议问题