solved: statement within while condition allowed?

hi,
I have two program versions which should behave the same way in my understanding, but they don’t.
The function gsm.CheckRegistration(false) in the following code always returns REG_REGISTERED.
Version 1 always prints “GSM not registered! 0”:

    hby=0;
    byte crg;
    while ((crg=gsm.CheckRegistration(false) != REG_REGISTERED) && (hby < 3))
    {
      hby++;
      delay(100);
    }
    delay(100);

    if (crg == REG_REGISTERED) Serial.println(F("GSM registered"));
    else {
      Serial.print(F("GSM not registered! "));
      Serial.println(crg);
    }

Version 2 always prints “GSM registered” as expected:

    hby=0;
    byte crg=gsm.CheckRegistration(false);
                       // mit true wird auch PARAM_SET_1 aktiviert
    while ((crg != REG_REGISTERED) && (hby < 3))
    {
      hby++;
      crg=gsm.CheckRegistration(false);
      delay(100);
    }
    delay(100);

    if (crg == REG_REGISTERED) Serial.println(F("GSM registered"));
    else {
      Serial.print(F("GSM not registered! "));
      Serial.println(crg);
    }

I don’t understand why version 1 always prints “GSM not registered! 0” inspite of gsm.CheckRegistration(false) returning REG_REGISTERED.

Explanation are very welcome :confused:

Because of operator precedence, this line from Version 1:

while ((crg=gsm.CheckRegistration(false) != REG_REGISTERED) && (hby < 3))

is equivalent to (note additional parentheses):

while ((crg=(gsm.CheckRegistration(false) != REG_REGISTERED)) && (hby < 3))

so crg is assigned either true or false, and is never equal to REG_REGISTERED in this line:

if (crg == REG_REGISTERED) Serial.println(F("GSM registered"));

To solve it, add parentheses:

while (((crg=gsm.CheckRegistration(false)) != REG_REGISTERED) && (hby < 3))

Thank you.
I guess I have seen many code like my first version from different programmers. But perhaps this was wrong too.

Try not to write obfuscated code like this - one day you’ll revisit this code and not understand it!

(hint: write a function to do the complicated thing, choose a good name for it, put just the function call in the while condition)