开发者

Return a typedef in C

开发者 https://www.devze.com 2023-04-08 02:44 出处:网络
In a .h file I defined: #define PAIR_TYPE(type1, type2)\\ typedef struct {\\// added \\ after edit type1 first;\\// added \\ after edit

In a .h file I defined:

#define PAIR_TYPE(type1, type2)\
    typedef struct {     \     // added \ after edit  
      type1 first;       \     // added \ after edit  
      type2 second;      \     // added \ after edit  
    };     // added ; after edit        
#define MAKE_PAIR(val1, val2) {val1, val2}
PAIR_TYPE(char *, uint32_t) mypair;
mypair foo();

In the .c f开发者_如何学Cile I used it like this:

mypair foo()
{
   mypair p;
   uint32_t bar = calculate();
   p = MAKE_PAIR("normal", target);
   return p;
}

However I get this error:

error: expected expression before ‘{’ token

The line it points is:

p = MAKE_PAIR("normal", target);

I don't know why it says '{' !!! there is no '{' at that line.


You need more backslashes on the lines after '{'

#define PAIR_TYPE(type1, type2)\
  typedef struct {\
    type1 first;\
    type2 second;\
  }


Yes there is! But it is hidden from your eyes by the preprocessor magic. Remember, the preprocessor is evil, and you are certainly over-using it.

The preprocessor just does textual substitution, so the code the compiler sees is actually:

p = {"normal", target};

And that is not valid C syntax. There, see, the '{'. That syntax is only valid in initialization, not in assignments:

mypair a = {"a", 1}; /* ok */
a = {"a", 1}; /* error */


In your PAIR_TYPE macro, you need to get rid of the semicolon at the end so that the name you give for the type is part of the typedef. Right now, when you do:

PAIR_TYPE(char *, uint32_t) mypair;

..you get:

typedef struct {
  char * first;
  uint32_t second;
}; mypair;

..which has a semicolon between the } and mypair that shouldn't be there.

You will also need to use a cast for your MAKE_PAIR macro to work the way you use it. Right now, the line:

p = MAKE_PAIR("normal", target);

..expands to:

p = {"normal", target};

..which won't work. But if you add a cast:

p = (mypair)MAKE_PAIR("normal", target);

..then the expanded line is:

p = (mypair){"normal", target};

..which can work since the type cast tells the compiler what the fields between the { and } should be. Though note that you're setting the char * in the first field to point at the literal "normal", not copying the string.


May be if you use c idiom to write macro as shown in the link, you will not have problem that you are experiencing. Please see http://c-faq.com/cpp/multistmt.html for details.

0

精彩评论

暂无评论...
验证码 换一张
取 消