Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if (a() && b != null)" will "a()" always be evaluated?

Tags:

c#

I have such code:

if (a() && b != null) {     b.doSomething(); } 

I need side effect of a() even if b is null. Is it guaranteed by C#? Or C# may omit a() call if b is null?

like image 248
Oleg Vazhnev Avatar asked Nov 23 '11 11:11

Oleg Vazhnev


People also ask

What is the use of IF ()?

The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect. So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

Can I do an IF THEN formula in Excel?

The IF-THEN function in Excel is a powerful way to add decision making to your spreadsheets. It tests a condition to see if it's true or false and then carries out a specific set of instructions based on the results. For example, by inputting an IF-THEN in Excel, you can test if a specific cell is greater than 900.

What are the 3 arguments of the IF function?

IF is one of the Logical functions in Microsoft Excel, and there are 3 parts (arguments) to the IF function syntax: logical_test: TEST something, such as the value in a cell. value_if_true: Specify what should happen if the test result is TRUE. value_if_false: Specify what should happen if the test result is FALSE.


2 Answers

Yes, a() will always be evaluated.

Since the condition is evaluated from left to right, a() will always be evaluated, but b != null will only be evaluated if a() returns true.

Here's an exact specification reference for you, from the C# Language Specification version 3.0. My emphases and elisions.

7.11.1 Boolean conditional logical operators

When the operands of && or || are of type bool [...] the operation is processed as follows:

  • The operation x && y is evaluated as x ? y : false. In other words, x is first evaluated and converted to type bool. Then, if x is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
like image 149
3 revs, 3 users 83% Avatar answered Oct 01 '22 14:10

3 revs, 3 users 83%


Yes, expressions are evaluated from left to right; so a() will always be called.

See the C# language spec (ECMA 334, paragraph 8.5):

Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.

like image 36
Jan Jongboom Avatar answered Oct 01 '22 12:10

Jan Jongboom