Evaluation on the right side of an assignment-Collection of common programming errors

This int c = (a==b) is exactly what I’d like to say in my C program, compiling with GCC. I can do it, obviously (it works just fine), but I don’t know whether it may cause undefined behavior. My program will not be compiled with some other compiler or in other architectures. Is this legal ANSI C? Thanks.

  1. It’s completely legal. if a is equal to b, then c will be 1. else, it will be 0.

  2. int c = (a == b);
    

    this is perfectly legal. Initialization is part of the C standard (C99 ยง6.7.8), the right hand side can just be any assignment-expression, including a == b (of course, assuming a and b are defined and have comparable type).

  3. It is perfectly valid if c is declared at block scope.

    When declared at file scope it is not valid because the initializer has to be a constant expression.

    a == b is an expression and in that sense is not different that another expression like a + b or a & b.

  4. Well, it depends on what the types of a and b are. If they are types that support equality check, then yes, it’s perfectly legal.

Originally posted 2013-11-09 21:23:11.