0

Macro on variable initialization in C.

#define abcd

char abcd c[] = "AJITH";

for(i=0;i<5;i++){
    printf("%c",c[i]);
}

output:- AJITH

Why didn't compiler show an error? What does it mean?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

0

Since the #define has no replacement text for abcd, any occurrence of abcd will basically be removed by the preprocessor, so

char abcd c[] = "AJITH";

becomes

char  c[] = "AJITH";
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
0

abcd is expanded to blank.

so char abcd c[] = "AJITH" is expanded to char c[] = "AJITH", which is perfectly fine.

Below is the output of your program only after preprocessing (gcc -E)

 char c[] = "AJITH";                                                            
 int i;                                                                         
 for(i=0;i<5;i++){                                                              
 printf("%c",c[i]);                                                             
 }  
Soumen
  • 1,068
  • 1
  • 12
  • 18
0

In the statement

#define abcd

there is no macro-body for macro-name. So it will replace macro-name with nothing.

After preprocessor stage your below code

#define abcd
int main(void) {
        char abcd c[] = "AJITH";
        for(int i=0;i<5;i++){
                printf("%c",c[i]);
        }
        return 0;
}

looks like this

int main(void) {
 char c[] = "AJITH";
 for(int i=0;i<5;i++){
  printf("%c",c[i]);
 }
 return 0;
}

Hence it prints AJITH

why didn't compiler shows the error? This #define abcd is a empty string & empty define are allowed according to C standard.

From C11 standard (n1570), ยง 6.10 Preprocessing directives

control-line:

# define identifier replacement-list new-line
   # define identifier lparen identifier-list(opt) ) replacement-list new-line
   # define identifier lparen ... ) replacement-list new-line
   # define identifier lparen identifier-list , ... ) replacement-list new-line

replacement-list:
    pp-tokens(opt)

As you can see above the replacement-list: and which is list of tokens & that can be empty.

Achal
  • 11,821
  • 2
  • 15
  • 37