简体   繁体   中英

proper use of the ternary operator in a function strToInt (C)

for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i)
    {
        intValue = string[i] - '0';

        minus == false ? result = result * 10 + intValue : 
            result = result * 10 - intValue;

    }

error: expression is not assignable screenshot - http://share.pho.to/AarcJ

https://codeshare.io/5Pdd7X

minus == false ? i = 0 : i = 1 minus == false ? i = 0 : i = 1 will be parsed as (minus == false ? i = 0 : i) = 1 because of operator precedence rule. After evaluation of minus == false ? i = 0 : i minus == false ? i = 0 : i , left side of operator = will become an rvalue, but assignment operator must have an lvalue as its left operand.
Change it to minus == false ? (i = 0) : (i = 1) minus == false ? (i = 0) : (i = 1)

Use (for example)

for (i = minus? 1:0; string[i].... etc

And...

result = result * 10 + minus? (-lastvalue) : lastvalue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM