Search code examples
cif-statementlogical-operatorsassignment-operator

Can assignment operator be used in if statements. As if statements are used Boolean expression


I was expecting an error in if(b=5), as the assignment operator is used in if statement.

Code: 
#include <stdio.h> 

int main() {
        
    int a=10, b=10; 
    if(b=5)
        a--; 
    printf("%d, %d", a, b--);
    return 0;
}

Solution

  • You expected it to raise an error because it seems a typo in the attempt to use the comparison operator ==, usually used in if-statements like this

    if ( b == 5 )
    

    The expression in the if-statement

    if ( b = 5 )
    

    is actually evaluated like every expression in C. In this case its evaluation is the value of the assignment 5, and since it is not zero it is equivalent to true in a boolean expression.

    It is probably a subtle typo, so that the author probably performed a comparison instead of that assigment. Anyways it doesn't raise an error because it is valid C.

    Fortunately, in many compilers a warning is raised. Make sure to enable all warnings in your compiler options, and to never ignore them. In this way you will avoid these subtle traps in the future.