954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

String

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();

}
ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

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 '!'.

deceptikon
Indubitably
Administrator
632 posts since Jan 2012
Reputation Points: 119
Solved Threads: 105
 

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!

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

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

zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
 

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

ram619
Light Poster
46 posts since Mar 2010
Reputation Points: 6
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You