简体   繁体   中英

How #define preprocessor really works in C

Please consider the following codes

#define FIRSTNAME ""
#define SECONDNAME "JOHN"
# define PATHSAVE(a) func(strcat(strcpy(tmpFileName, appDir), a))
int main() {
  PATHSAVE(FIRSTNAME SECONDNAME);
}

By analyzing I found out that value "John" is passed to the function PATHSAVE. By I couldnt understand why two parameters are used in this function PATHSAVE(FIRSTNAME SECONDNAME)

What you wrote will be expanded as follows

func(strcat(strcpy(tmpFileName, appDir), "" "JOHN"));
                                         ^^ ^^^^^^
                                         || ||||||
                                         || SECONDNAME
                                         ||
                                         FIRSTNAME

Passing two parameters to a macro require them to be separated by , and not by a space

PATHSAVE(FIRSTNAME SECONDNAME);

will expand to PATHSAVE("JOHN") as the preprocessor will concatinate the 2 strings together.

This will then be further expanded to

func(strcat(strcpy(tmpFileName, appDir), "JOHN"))

You can use the c pre processor if you want to know what is going on.

I pasted your code in a file named ex.c, here is the output of:

cpp ex.c

# 1 "ex.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "ex.c"



int main() {
  func(strcat(strcpy(tmpFileName, appDir), "" "JOHN"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM