char s[]="the cocaine man";

int i=0;
char ch;

ch=s[++i];
printf("%c ",ch);

ch=s[i++];
printf("%c ",ch);

ch=i++[s];
printf("%c ",ch);

ch=++i[s];
printf("%c ",ch);

output = h h e !

i got the outputs like this ...can anyone please what are the reasons for these outputs !! is it compiler dependent ?? if yes , why ??

Recommended Answers

All 3 Replies

char s[]="the cocaine man";
int i=0;
char ch;

ch=s[++i];
printf("%c ",ch);

You pre increment the value of " i " which now becomes 1 and u access ch = s [1] which is 'h' the second char of the array.

ch=s[i++];
printf("%c ",ch);

This time u use the post increment operator i ++ which causes the prev value of " i " to be used which is 1 and then increments it. So after this expression the value of i is now 2.

ch=i++[s];
printf("%c ",ch);

Arrays can be accesssed as arrayName [index] or index [arrayName] . For eg i can access an array as 3 [arrayName] = 'a'; which will set the fourth element of the array to character a.
Hence u use indirectly ch = 2 [s]; which is 'e'.
At this point the value of i becomes 3.

ch=++i[s];
printf("%c ",ch);

You now increment the ascii value of the character at position 3 which is a space ' '. The next character in the ASCII table after ' ' is ! hence the output.

output = h h e !


Hope it helped,
Bye.

thanks for the nice explaination !!!!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.