From the course: Secure Coding in C

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Using an assignment as a condition

Using an assignment as a condition - C Tutorial

From the course: Secure Coding in C

Start my 1-month free trial

Using an assignment as a condition

- [Instructor] A common programming mistake in C is to use a single equal sign, which is the assignment operator, instead of the double equal sign as a comparison. This assignment test could also lead to undefined behavior if it's handled improperly. So in this code, an assignment is made at line nine. The assignment is contained in parentheses, which avoids a compiler warning. For example, it might be the programmer's intent to compare variables A and B. In that case, two equal signs would be used instead of one. But here, one equal sign is used, so the value of B is assigned to variable A, and then the result of this operation, which is the original value of variable B, is what the if condition evaluates. If that original value, the value of variable B, is non-zero, the condition is true. If the value of variable B is zero, the condition is false, and the code runs as predicted. Of course, there's a better way to…

Contents