Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code resolved to true?

Tags:

c

int main() {
    int a = 1;
    int b = 0;

    if (a = b || ++a == 2)
        printf("T: a=%i, b=%i", a, b);
    else
        printf("F: a=%i, b=%i", a, b);

    return 0;
}

Let's take a look at this simple code snippet. Result is: T: a=1, b=0

Why? (note a=b uses assignment operand, not comparison)

What I understand here, is that zero is assigned to a, then a is incremented to 1. 1 is not equal to 2. So result should indeed be a=1, b=0. But why is this condition evaluated to true? Neither of (a=b) or (++a == 2) is true ... What did I miss?

Here is other short program that prints F as expected:

int main() {
    int a = 1;
    int b = 0;

    if (a = b) printf("T"); else printf("F");

    return 0;
}
like image 766
Xorty Avatar asked Jan 07 '12 16:01

Xorty


People also ask

How do you know when a promise is resolved?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

Does code run after resolve?

resolve() is not a JS control statement that magically would have the effect of return , it's just a function call, and yes, execution continues after it.

What happens if promise is not resolved?

So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

How do I return a resolve promise?

Promise resolve() method:If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.


2 Answers

You have confused yourself with misleading spacing.

if (a = b || ++a == 2)

is the same as:

if (a = (b || ((++a) == 2)))

This actually has undefined behavior. Although there is a sequence point between the evaluation of b and the evaluation of ((++a) == 2), there is no sequence point between the implied assignment to a and the other write to a due to the explicit = assignment.

like image 158
CB Bailey Avatar answered Sep 25 '22 00:09

CB Bailey


Actually, assignment has the lowest operator precedence so your if statement is equivalent to:

if ( a = ( b || ( ++a == 2 ) ) )

So you're assigning a to 1 but also incrementing it in the same expression. I think that leads to undefined behavior, but the end result is that a is 1 in your compiler.

like image 22
David Grayson Avatar answered Sep 24 '22 00:09

David Grayson