简体   繁体   中英

How does C evaluate 2 minuses with 2 operands?

Consider:

    int a;
    a = -3--3;
    printf("%d", a);

The 2nd line (a = -3--3) produces a compile time error.
On adding an extra pair of brackets as follows:

    int a;
    a = -3 - (-3);
    printf("%d", a);

the error disappears.

Since the brackets remove the error I believe that some ambiguity must have caused it.

But I don't see why the compiler is confused. I try to subtract -3 from -3 .


All help is appreciated.

C has a unary decrement operator that's spelled -- , and a "maximal munch rule" that makes it recognize that operator rather than a minus sign and a negative sign even where the latter would make more sense. For about half a dozen accompanying reasons, 3 -- 3 doesn't make sense, and you get an error.

If you'd said a = -3 - -3; , instead of cramming everything together like your space bar's broken, you'd have been fine. :PA space between the two operators keeps C from seeing a -- .

Taking for granted that you know that "--" represents a unary operator for pre/post decrement, it is easy to understand the reason why the compilers throw an error.

The parser of the C compiler reads the first minus sign, then, it expects either a number (meaning that your intention is to perform a regular substraction) or another minus sign (meaning that your intention is to perform a pre-decrement unary operation. In your case, you are basically telling the C compiler that you want to perform a pre-decrement. It doesn't make sense for two reasons:

a) If your intention was actually to perform a pre-decrement operation, then you are missing an extra binary operator (eg "+"), just like this: a = -3 + (--3).

b) The other reason (which makes my previous example also to throw a compile time error, is that you are trying to perform a unary operation on a constant. Totally non-sense, since the compiler reserves memory for a constant that you are, later on, trying to modify.

Hope this helps to get the concept of expressions in "C", a source of many headaches for beginners (and even for experts sometimes!).

My advice: keep the code clean, meaningful and use braces as much as common sense tells, which is the contrary that you did, in my opinion.

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