The output of this code is "hhe!". Upto "hhe" I can figure out what is happening but, where does this "!" came from? ASCII value of "!" is 33 and here I don't think we are anyhow getting this value. Thanks in advance

#include<stdio.h>
#include<conio.h>

void main()
{
 static char s[25]="The cocaine man";
int i=0;
char ch;
clrscr();
ch=s[++i];
printf("%c",ch);
ch=s[i++];
printf("%c",ch);
ch=i++[s];
printf("%c",ch);
ch=++i[s];
printf("%c",ch);
getch();

}

Recommended Answers

All 4 Replies

When you say ch=i++[s]; it means ch=(i++)[s]; , but when you say ch=++i[s]; it means ch=++(i[s]); . It's totally confusing because intuition says it should be ch=(++i)[s]; . But that's where the '!' is coming from. i is 3 at that point, and the next character after ' ' in ASCII is '!'.

Placing the ++ operator before a variable means you would like to increment the value stored in the variable before using it. Placing the ++ after a variable means you would like to use the current value of the variable, then increment it before executing the next line.

int i = 0;
int j = 0;

/*
 * This is the same as:
 * i = i + 1;
 * int k = 0;
 */
int k = ++i; // k will be 1

/*
 * This is the same as:
 * int l = i;
 * i = i + 1;
 */
int l = i++; // l will be 0

Hope that helps!

you could also try to print out the value of i while incrementing it to see the changes that happens and its current value for yourself

Thanks a lot to all of you.....got it now :) .........

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.