Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Postfix ++/-- categorized as primary Operators in C#?

Currently I'm teaching a class of C++ programmers the basics of the C# language. As we discussed the topic operators I used C# standard categories of primary, unary etc. operators.

One of the attendees felt puzzled, because in the C# standard the "postfix ++/--" have been put in the category of primary operators rather than the "prefix ++/--". Her rationale behind this confusion was, that she would rather implement the C++ operator "postfix ++/--" in terms of the operator "prefix ++/--". In other words she would rather count the operator "prefix ++/--" as a primary operator. - I understand her point, but I can't give to her a rationale behind that. OK the operators "postfix ++/--" have a higher precedence than "prefix ++/--", but is this the only rationale behind that?

The spec mentioned it in section "14.2.1 Operator precedence and associativity".

So my very neutral question: Why are Postfix ++/-- categorized as primary Operators in C#? Is there a deeper truth in it?

like image 899
Nico Avatar asked Aug 13 '11 08:08

Nico


People also ask

What is postfix operator in C?

C # in Telugu Postfix operators are unary operators that work on a single variable which can be used to increment or decrement a value by 1(unless overloaded).

What type of operator uses postfix and prefix?

Increment ++ and Decrement -- Operator as Prefix and Postfix In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1.

What is the difference between prefix and postfix operator in C?

Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased). Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.


1 Answers

Since the ECMA standard itself does not define what a 'Primary' operator is, other than order of precedence (i.e. coming before 'Unary') there can be no other significance. The choice of words was probably bad.

Take into account that in many C-link languages, postfix operators tend to create a temporary variable where the expression's intermediate result is stored (see: "Prefer prefix operators over postfix" at Semicolon). Thus, they are fundamentally different from the prefix version.

Nonetheless, quickly checking how Mono and Visual Studio compile for-loops using the postfix and prefix forms, I saw that the IL code produced is identical. Only if you use the postfix/prefix expression's value does it translate to different IL (only affecting where the 'dup' instruction in placed), at least with those implementations mentioned.

like image 73
Yuval Avatar answered Sep 20 '22 15:09

Yuval