Saturday, December 31, 2011

2.1.6. The risk of assignment inside an "if"

Beware of the equality operator: remember that the format is "if (a == b)" ... If we do not remember it and write "if (a = b)", we are trying to assign to "a" the value "b".

In some C compilers, this could be a serious problem, because in C language it is acceptable to assign a value within an "if" (although most modern compilers would warn us that it might be an unintended assignment).

For the C# language, such risk does not exist, because in C# the "condition" must be strictly "true" or "false", so an assignment would lead to a compile error: "Can not implicitly convert type 'int' to 'bool'". This is the case in the following program:



/*---------------------------*/
/* C# Example #11: */
/* example11.cs */
/* */
/* Conditions with if (7) */
/* incorrect comparison */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
 
using System;
 
public class Example11
{
public static void Main()
{
int number;
 
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number = 0)
Console.WriteLine("The number is zero.");
else
if (number < 0)
Console.WriteLine("The number is negative.");
else
Console.WriteLine("The number is positive.");
}
}
 

No comments:

Post a Comment