Search code examples
cif-statementbooleanassignment-operator

How the assignment statement in an if statement serves as a condition?


if ((vnd = (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend))) {...}

Can you tell me why it is an assignment but not a boolean expression in the brackets ? And in what situation this assignment can be considered "true" or "false" ?


Solution

  • Quoting C11, chapter §6.5.16, Assignment operators (emphasis mine)

    An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,111) but is not an lvalue.

    So, first the assignment will happen, and then, the value that has been assigned will be used as the conditional statement in if.

    So, in case of

    if (p = 0 )
    

    will evaluate to FALSE and

    if (p = 5)
    

    will be TRUE.