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.
-
It’s completely legal. if
a
is equal tob
, thenc
will be 1. else, it will be 0. -
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, assuminga
andb
are defined and have comparable type). -
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 likea + b
ora & b
. -
Well, it depends on what the types of
a
andb
are. If they are types that support equality check, then yes, it’s perfectly legal.
Originally posted 2013-11-09 21:23:11.