Home > Blockchain >  Whether the functions in _generic can use macro functions defined by define?
Whether the functions in _generic can use macro functions defined by define?

Time:01-14

#define a printf("I am int type !!~\n");

#define b printf("I am double type !!~\n");

#define foo(x) _Generic(x, int : a, \
                          double : b)(x)

int main(){
    foo(123);  // foo_int(123) // I am int type !!~
    system("pause");
    return 0;
}

Why does this give an error?and The compiler tells me: Should type ")"

When I change the function call in _Generic to one that is not defined by define, the compiler does not throw an error.

CodePudding user response:

Whether the functions in _generic can use macro functions defined by define?

The identifiers inside _Generic will be expanded before _Generic takes place. In that sense, you can use macros.

Why does this give an error?

foo(123); expands to

_Generic(123, int : printf("I am int type !!~\n");, double : printf("I am double type !!~\n");)(123);

The ; before , inside _Generic are just invalid, and the (x) after _Generic(...)(123) also doesn't make sense. The produced code is not following the syntax of C programming language.

CodePudding user response:

The operands of the _Generic cases must be expressions (specifically an assignment-expression). printf("I am int type !!~\n"); is a statement, not an expression.

When you remove the semicolon, it is an expression. Then _Generic(x, int : a, double : b) would be fine, but you have (x) after it. Why?

After processing of the _Generic, the expression is basically printf("I am int type !!~\n"). That is a complete function call. Putting (x) after it to make printf("I am int type !!~\n")(x) attempts to make another function call, but that does not work since printf returns an int, not a pointer to a function. Remove (x).

  •  Tags:  
  • c
  • Related