jessie jessie - 1 year ago 73
C Question

c programming language exercise 3-2 print escape characters in array

I want to print escape characters like newline and tab into visible escape sequences like \n and \t So I think I should print two \ then n to print the visible \n. But it doesn't work. The answer print n then two \ and it works. And I don't know why. Here's my code.

case '\n' :
s[j] = '\\';
s[j++] = 'n';

And heres the answer

case '\n':
s[j++] = '\\';
s[j] = 'n';


Answer Source

You need to know the following about increments/decrements:

  1. When using them as complete statement (on their own), i++ and ++i are equivalent.

  2. When using them in an expression, i++ will use then current value of i in the expression and increase i after the expression has been evaluated whereas ++i will first increase the value of i, then evaluate the expression.


int s[2] = {6,7};
int i = 0;
printf("%d", s[i++]);  //prints 6 then sets i equal to 1


int s[2] = {6,7};
int i = 0;
printf("%d", s[++i]);  //Sets i equal to 1 then prints 7

In your case this means that when you use s[j++] you are using the same j as in the line above before incrementing it (thus overwriting the value of s[j] you had just set).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download