Reputation: 20119
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.
Upvotes: 1
Views: 113
Reputation: 145829
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
.
Upvotes: 1
Reputation: 258568
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.
Upvotes: 0
Reputation: 523254
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).
Upvotes: 1
Reputation: 5456
It's completely legal. if a
is equal to b
, then c
will be 1. else, it will be 0.
Upvotes: 4