←back to thread

The C23 edition of Modern C

(gustedt.wordpress.com)
397 points bwidlar | 3 comments | | HN request time: 0.806s | source
Show context
belter ◴[] No.41850897[source]
Important reminder just in the Preface :-)

Takeaway #1: "C and C++ are different: don’t mix them, and don’t mix them up"

replies(6): >>41850960 #>>41851047 #>>41851166 #>>41851693 #>>41853183 #>>41855660 #
jpcfl ◴[] No.41851047[source]
Bjarne should have called it ++C.
replies(2): >>41851328 #>>41854437 #
card_zero ◴[] No.41851328[source]
Because people choose to use pre-increment by default instead of post-increment?

Why is that?

replies(4): >>41851427 #>>41851557 #>>41851650 #>>41853498 #
1. int_19h ◴[] No.41851650[source]
It should be ++C because with C++ the value you get from the expression is the old one.

If you're asking why people use pre-increment by default instead of post-increment, it's mostly historical. The early C compilers on resource-constrained platforms such as early DOS were not good at optimization; on those, pre-increment would be reliably translated to a simple ADD or INC, whereas code for post-increment might generate an extra copy even if it wasn't actually used.

For C++ this was even worse with iterators, because now it depended on the compiler's ability to inline its implementation of postfix ++, and then prove that all the copies produced by that implementation have no side effects to optimize it to the same degree as prefix ++ could. Depending on the type of the underlying value, this may not even be possible in general.

The other reason is that all other unary operators in C are prefix rather than postfix, and mixing unary prefix with unary postfix in a single expression produces code that is easy to misunderstand. E.g. *p++ is *(p++), not (*p)++, even though the latter feels more natural, reading it left-to-right as usual. OTOH *++p vs ++*p is unambiguous.

replies(2): >>41851765 #>>41854531 #
2. card_zero ◴[] No.41851765[source]
K&R seems to use pre-increment early on, then post-increment consistently (or a lot, anyway, I haven't done a thorough check) after chapter 3, in situations where either would do. In fact, after introducing post-increment at 2.8.
3. jpcfl ◴[] No.41854531[source]
> It should be ++C because with C++ the value you get from the expression is the old one.

You get it!