Search code examples
cpointersoperator-precedence

Pointer in C (while(*s1++ = *s2++))


For the below program

#include<stdio.h>

int main()
{
    char str1[] = "India";
    char str2[] = "BIX";
    char *s1 = str1, *s2=str2;
    while(*s1++ = *s2++)
        printf("%s", str1);

    printf("\n");
    return 0;
}

How the condition in while loops gets evaluated? I can see the similar post in stack overflow here, but they didn't give explanation how * operator has greater precedence than postfix operator.But actually, postfix operator has greater precedence than * (Derefernce) operator. Precedence table for our reference here

Please explain how this code prints below output

BndiaBIdiaBIXia 

Solution

  • Operator precedence and order of execution is not necessarily the same thing.

    *s1++ = *s2++
    

    Is evaluated by the compiler as follows:

    1. Compiler sees "++" which has the highest precedence. As it is the post-increment operator, it simply makes note of the fact that the pointer needs to be incremented after the evaluation of the expression is done.
    2. Compiler sees "*" operator, telling it that it should dereference s2, and use that as the RHS
    3. Same on the left side of the assignment, the char at s1 is set to the char's value at s2
    4. Compiler gets back to it's note that pointers need to be incremented after expression evaluation and does so.

    Even if ++ is of higher precedence as *, it is still done last. Precedence here just means the post-increment operation has to be done to the pointer, and not to the value at the pointer