问题
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" ?
回答1:
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.
回答2:
The logical operator for "is equal to" is ==
When you're saying vnd = (struct...
you are assigning everything after =
to the variable vnd
. If you want a true or false you need to use ==
回答3:
C considers anything non-zero to be true
, and anything 0 to be false.
This assignment's value is equal to the value it assigns to vnd
, in this case, a struct diam_vnd_t *
. The if statement checks whether or not vnd
is NULL
after the assignment.
This would be equivalent to:
vnd = (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend);
if (vnd) {...}
回答4:
Assignment is always done with one equal sign. =
int i;
i = 0; //assignment
This assigns 0 to an integer called i
.
The same thing happens with your if statement. Whether or not it is in an if statement is irrelevant.
(vnd = (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend))
To do a boolean expression, you need to use ==
.
(vnd == (struct diam_vnd_t *)g_hash_table_lookup(vendors,vend))
This will return true or false based on the comparison of the 2 items
来源:https://stackoverflow.com/questions/37166250/how-the-assignment-statement-in-an-if-statement-serves-as-a-condition