Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does macro expansion add a space sometimes?

If I do this:

#define F a
F/

It expands to a/ godbolt

If I do this:

#define F /
F/

It expands to / / with a space in between goodbolt

But if I convert it to a string, and print it, it doesn't add any spaces goodbolt:

#include <stdio.h>

#define STR_IMPL(x) #x
#define STR(x) STR_IMPL(x)

#define F /


int main() {
  puts(STR(F/));
}

Why is there a space in between, but only some of the time? Is it allowed to add more spaces in other cases?

like image 834
Ayxan Haqverdili Avatar asked Jan 25 '23 11:01

Ayxan Haqverdili


1 Answers

Macros work on the token level. Spaces are added when printing the result in string form to disambiguate.

F/ is two tokens, F and /. After macro expansion, it still needs to be two tokens, / and /. But if you print them next to each other, it becomes //, which is just one token (a comment). So there needs to be a space in-between.

Long story short: yes, macro expansion can add spaces, because spaces don't matter at the level macros operate at.

like image 195
Sebastian Redl Avatar answered Feb 04 '23 16:02

Sebastian Redl