1

For

char *p="abcd";

i have following two statements in the code

++*p;

and second one

*++p;

these two are producing the same result but is there any difference on the way these two are implemented?Also please clear which one has higher precedence "++" or "*".Thanx

OldSchool
  • 2,123
  • 4
  • 23
  • 45
  • The two statements only happen to produce the same value because of the specific string you initialized `p` with (and because your compiler happened not to allocate the string in memory marked read-only). – user2357112 Mar 07 '14 at 05:18
  • Try the string "blah" to see that they do **not** produce the same result. – Cheers and hth. - Alf Mar 07 '14 at 05:19
  • @Cheersandhth.-Alf but why it is producing the same result – OldSchool Mar 07 '14 at 05:25
  • @Bayant_singh: because incrementing the ASCII code for "a", which happens to be 97, produces the ASCII code for "b", namely 98, which happens to be the value you have placed as second item in the array (string) -- and the other expression produces the second item... – Cheers and hth. - Alf Mar 07 '14 at 09:55

1 Answers1

1

Precedence table

Refer the precedence table operators with higher precedence will be evaluated first.

in your case your using prefix increment ++ which has the same precedence level as deference operator *. so when you have both in the same expression Associativity of it should be considered which is right to left

++*p will be equivalent to ++(*p) the pointer is deference'd first then the value is incremented.

 char *p="abcd";

i.e *p is equal to a and ++ on character will give you b

*++p will be equivalent to *(++p) the pointer is incremented first then deference'd

i.e ++p will point to b in the string then then * deference will give you the b at position 2.

Change your input string you get a different answer. same answer your getting is just as the operation on the first character matches the operation for the second

KARTHIK BHAT
  • 1,410
  • 13
  • 23