Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are assignments in conditions bad?

I am using NetBeans for PHP 6.5.

In my code I frequently use the following type of command:

if (($row = $db->get_row($sql))) {         return $row->folder;     } else {         return FALSE;     } 

Netbeans tells me that I should not be using assignments in the IF statement.

Why ?

like image 311
William Macdonald Avatar asked Nov 25 '08 13:11

William Macdonald


People also ask

What does assignment in conditional expression mean?

It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it's '==' or '==='. To assign a value to a variable it's '=' Submitted by Clarisse.

Can we use assignment operator in if condition?

Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)


1 Answers

They are not bad, but they can lead to dangerous mistakes.

In c like languages, where an assignment is an expression, (to support for example a=b=c=1;) a common error is:

if (a = 1) { .. } 

But you wanted to have

if (a == 1) { .. } 

Some developers have learned to type

if (1 == a) { .. } 

To create an error if one '=' is forgotten. But I think that it does not improve the readability.

However modern compilers, give a warning if you write

if (a = 1) { .. } 

which I think is a better solution. In that case you are forced to check if it was what you really meant.

like image 119
Toon Krijthe Avatar answered Sep 21 '22 12:09

Toon Krijthe