Mostafa Ezz
Mostafa Ezz

Reputation: 55

assiging values and compare at the same line how does it work?

The condition of while loop in the below function

void strcpy(char *s, char *t)
    {
    int i;
    i = 0;
    while ((s[i] = t[i]) != '\0')
    i++;
    }

the condition here (s[i] = t[i]) != '\0' will produce either 0 or 1 does it compare the assigning statement to null character? or the value of the i'th element of the 2 arrays to null character?

Upvotes: 0

Views: 48

Answers (2)

Proper
Proper

Reputation: 43

It works based on operator precedence. Highest to lowest:

  1. ( )
  2. !=
  3. =

So in your example code, because of the parentheses, assignment happens first then the comparison with '\0'.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

The assignment expression has a value, which is the left operand after the assignment.

In this example, the condition is testing s[i] != '\0' (after executing s[i] = t[i]).

Upvotes: 2

Related Questions