How does the C preprocessor work?

I made the code snippet easier to explain

// Example 1

#define sum2(a, b) (a + b)
#define sum3(a, b, c) (sum2(a, sum2(b, c)))

sum3(1, 2, 3)    // will be expanded to ((1 + (2 + 3)))


// Example 2

#define score student_exam_score
#define print_score(student_exam_score) printf("%d\n", score)
#undef  score

print_score(80); // will be expanded to printf("%d\n", score);
                 // but not printf("%d\n", 80); that I expect

The first one is intuitive and that code types exist in several places, such as finding a maximum or minimum number. However, I want to use this method to make my code clean and easy to read, so I replace a few words in the macro with a shorter and more meaningful name.

AFAIK, the C preprocessor only runs once per compilation unit and only performs line replacements, but why print_scorecan't you expand to printf("%d\n", 80);?

This is the replacement procedure that I assume:

#define score student_exam_score
#define print_score(student_exam_score) printf("%d\n", score)
#undef  score

print_score(80);

//  --> 

#define score student_exam_score  // runs this first
#define print_score(student_exam_score) printf("%d\n", student_exam_score)  // changed
#undef  score

print_score(80);

//  --> 

#define score student_exam_score
#define print_score(student_exam_score) printf("%d\n", student_exam_score)  // then this
#undef  score

printf("%d\n", 80);  // changed
+4
source share
1 answer

. , score - undefined . , print_score , student_exam_score, . , , , score undefined .

#undef score print_score, , (score , student_exam_score ).

, score print_score . , #undef score , score .

. :

#define foo bar
#define baz(bar) (foo)
baz(123)

:

    baz(123)
->  (foo)
->  (bar)

. , foo .

:

#define foo bar
#define baz(bar) (foo)
#undef foo
baz(123)

:

    baz(123)
->  (foo)

, foo . baz, , . , .

+3

All Articles