Got Ya



An error which almost every C programmer has made is shown below:
	main()
	{
	   int left=10;

	   if ( left = 5 )
	   {
	      puts(" Values are equal...");
	   }
        }

The program assigns 5 to the variable left and returns 5. This is interpreted as TRUE and causes the puts statement to be executed everytime.

Here is the corrected program.

	main()
	{
	   int left=10;

	   if ( left == 5 )		/* Double equals required. */
	   {
	      puts(" Values are equal...");
	   }
        }


A good way to avoid making this mistake is to get into the habit of always putting the constant first in any comparison. If the initial (incorrect) if statement had been written if ( 5 = left ) then the compiler would have thrown an error since the value of left can not be assigned to the number 5.

See Also:

Coding idioms.


Top Master Index Keywords Functions


Martin Leslie