myheadhurts myheadhurts - 2 months ago 8
C Question

Weird interaction with pointers in C

So, I have discovered something that's been bugging me for a while. I am still new to C language.

The code that I am talking about is here and its an implementation of strcmp : http://pastebin.com/VeHGm8sD

The weird thing about this program is that if you change at lines 12 respectively 13

*first_string++; // should increment value of char ??
*second_string++;


to

first_string++; // should increment address
second_string++;


They both increment the address however. How is that possible ?

Answer

because of the operator precedence.

That form would increment the char:

(*first_string)++;

or

++*first_string;

as @JonathanLeffler pointed. In this particular case it is not important when the char pointed by first_string gets incremented as you prematurely drop the result by terminating the statement. In all other cases when this expression is a sub-expression of some other expression you should clearly understand which form of ++ you use.

In your example the *first_string++ has a value and type of char, while first_string++ is a pointer

Comments