c++ - Preprocessor directive not working in for loop -


i want know how preprocessor directives evaluated, when placed in loop in c/c++? following code, uses directive in loop, doesn't work. why so?

main.cpp

#include <stdio.h> class student { public:     int roll;     int marks;      student()     {         roll = 10;         marks = 0;     } };      int main() {     printf("hello, world!\n");     int icounter;      char attr[][6] = {"roll", "marks"};      student std;  #define print1(std, x) printf("%d", std.##x);     (icounter = 0; icounter < 2; icounter++)     {         print1(std, attr[icounter])     }      return 0; } 

the preprocessor pre-compilation phase. code generator and, such, has no knowledge of or interaction for loops.

you cannot iterate on class's members in manner.

here's preprocessed code looks (i've omitted header expansions obvious reasons):

class student { public:     int roll;     int marks;      student()     {         roll = 10;         marks = 0;     } };      int main() {     printf("hello, world!\n");     int icounter;      char attr[][6] = {"roll", "marks"};      student std;      (icounter = 0; icounter < 2; icounter++)     {         printf("%d", std.attr[icounter]);     }      return 0; } 

as attr not member of std (terrible name object; please change it), can see how not going "work" intend.

furthermore, your macro inherently broken , produces error, because using ## shouldn't. if code wanted, proper definition simply:

#define print1(std, x) printf("%d", std.x); 

Comments