Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48197

What is the boolean result of assign null to a variable

I almost sure those two codes are equivalent, but not sure why.

First is the how I usually do it, i think the safe and more readable way.

string userLine = Console.ReadLine();

while (userLine != null) {
    // do things with userLine
    userLine =  Console.ReadLine();
}

Second one works but not sure why. Because Im comparing an assigment to null.

string userLine;

while ((userLine =  Console.ReadLine()) != null) {
    // do things with userLine
}

Upvotes: 0

Views: 75

Answers (4)

Varun Mishra
Varun Mishra

Reputation: 121

In most likely scenario it is a function call and on return of the function the return value is stored either in done data GPR(general purpose register) or at top of stack. So, the next statement will just use that location and compare against null. Now you see fit generated code it doesn't make any difference... If you want to be sure, generate the assembly file during compilation and check for yourself. All compilers provide option to keep generated files...

Upvotes: 0

Mukesh
Mukesh

Reputation: 410

The second code works because != operator has left associativity. So that first

(userLine =  Console.ReadLine())

execute, after that comparison happen. And you are right the first approach is more readable. If you want to get more information about associativity please refer https://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx

Upvotes: 0

atp9
atp9

Reputation: 890

The reason behind it works well is because, parenthesis () have highest operator precedence. Once assignment is done, compile will compare the the value of that variable to the null.

Having assignment in parenthesis chains your assignment. And that is the reason, it works.

Not only on Assignment, it works with return values too.

return (value = Console.ReadLine());

But yes, the first one is more readable approach.

Upvotes: 0

Habib
Habib

Reputation: 223277

I believe you are thinking that the assignment operation doesn't return any value or returns a Boolean value. That is not correct.

See: = Operator

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result.

So your statement

while ((userLine =  Console.ReadLine()) != null) {

is getting the value from Console.ReadLine assigning the result to userLine and returning the same value, which is compared with null.

Upvotes: 5

Related Questions