3
#include<stdio.h>
void main()
{
    int a,b,c;
    for(b = c = 10; a = "- FIGURE?, UMKC,XYZHello Folks,TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"[b+++21];)
    {
        for(;a-->64;)
        {
            putchar((++c == 'Z') ? (c = c/9) : (33^b&1));
        }
    }
    getch();
}

Above program in c language gives the output as map of India. In the above program outer for loop has 2 slots and the third one is left empty. However I understood how the program works but the doubt is that the condition slot of the outer for loop works as an assignment slot. Syntactically and logically this should be wrong but it works. According to the value in array index, ASCII code of corresponding char is assigned variable a.
How this works?

haccks
  • 104,019
  • 25
  • 176
  • 264
Ashish Khatri
  • 493
  • 5
  • 13

1 Answers1

6

The condition slot of the outer for loop assigns to a one of the characters of the string literal, at the same time incrementing b. Because the assignment operator also returns the assigned value, the condition of the outer for loop becomes the value of some of the characters of the string literal. Because strings are '\0'-delimited in C, the condition is true until the expression b++ + 21 reaches the end of string (then the last (extra) character of the string is returned, and it's equal to 0, thus evaluating as false)

In fact, this is an obfuscated and more complex version of a common C idiom for iterating a string, which looks like this:

char *string = "my string";
int i;
for (i = 0; string[i]; ++i)
    /* do something with string[i] */

which can be simplified to:

int i = 0;
for (; string[i++]; )
    /* do something with string[i] */

Moreover, the current character can be extracted to a separate char variable c:

int i = 0;
char c;
for (; c = string[i++]; )
    /* do something with c */

A while loop can be used instead as well:

while (c = string[i++])
    /* do something with c */
Michał Trybus
  • 11,526
  • 3
  • 30
  • 42