惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
T
The Exploit Database - CXSecurity.com
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
月光博客
月光博客
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
NISL@THU
NISL@THU
爱范儿
爱范儿
S
Securelist
博客园 - 叶小钗
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
D
DataBreaches.Net
G
GRAHAM CLULEY
P
Proofpoint News Feed
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
Jina AI
Jina AI
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
博客园 - 【当耐特】
H
Help Net Security
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss

Hacker News

Introducing Claude Opus 4.7 Qwen Studio The Future of Everything is Lies, I Guess: Where Do We Go From Here? GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis Ancient DNA reveals pervasive directional selection across West Eurasia [pdf] Moving a large-scale metrics pipeline from StatsD to OpenTelemetry / Prometheus GitHub - Nightmare-Eclipse/RedSun: The Red Sun vulnerability repository GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - macOS26/Agent: Any AI, replaces Claude Code, Cursor, OpenClaw. Over 18 LLM providers (Claude, OpenAI, Gemini, Ollama, Zai, HF, Qwen) wired into a native Mac app that writes code, builds Xcode projects, bumps versions, manages git, automates Safari, use AppleScript, JS or Accessibility, extend Agent! w/ MCP Servers, run tasks from your iPhone via Messages. YouTube now lets you turn off Shorts I Made a Terminal Pager Burgers | マクドナルド公式 Commands — HackerNews CLI documentation ChatGPT for Excel PiCore - Raspberry Pi Port of Tiny Core Linux Live Nation illegally monopolized ticketing market, jury finds Google Broke Its Promise to Me. Now ICE Has My Data. Founding Engineer at Adaptional | Y Combinator CRISPR takes important step toward silencing Down syndrome’s extra chromosome GitHub - saffron-health/libretto: The AI toolkit for building reliable browser automations US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf] Unexpected €54k billing spike in 13 hours: Firebase browser key without API restrictions used for Gemini requests Retrofitting JIT Compilers into C Interpreters IPv6 – Google The Accursèd Alphabetical Clock Cybersecurity Looks Like Proof of Work Now Fragments: April 14 Cal.com Goes Closed Source: Why AI Security Is Forcing Our Decision | Cal.com - Scheduling Software for Online Bookings Laravel raised money and now injects ads directly into your agent When moving fast, talking is the first thing to break Too much Discussion of the XOR swap trick – Heather Cafe Introduction to Spherical Harmonics for Graphics Programmers The Grand Line Building a Z-Machine in the worst possible language High-Level Rust: Getting 80% of the Benefits with 20% of the Pain GitHub - duguyue100/midnight-captain: Inspired by Midnight Commander, tailored to my taste. How to build a `git diff` driver · Jamie Tanna | Software Engineer Center for Responsible, Decentralized Intelligence at Berkeley The Local Universe’s Expansion Rate Is Clearer Than Ever, but Still Doesn’t Add Up - A new synthesis of astronomical measurements confirms a persistent mismatch that could point to physics beyond current models The air throughout our homes is infused with microplastics. But there are things you can do to breathe less of them The disturbing white paper Red Hat is trying to erase from the internet – OSnews The Future of Everything is Lies, I Guess: Annoyances ‘Abhorrent’: the inside story of the Polymarket gamblers betting millions on war Productive procrastination — Max van IJsselmuiden maps, territory and LMs 447 Terabytes per Square Centimetre at Zero Retention Energy: Non-Volatile Memory at the Atomic Scale on Fluorographane Show HN: Pardonned.com – A searchable database of US Pardons 20 Years on AWS and Never Not My Job The Seasons are Wrong Artemis II crew splashes down near San Diego after historic moon mission We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs How a dancer with ALS used brainwaves to perform live On filing the corners off my MacBooks Installing every* Firefox extension OpenClaw’s memory is unreliable, and you don’t know when it will break Steve Blank Nowhere Is Safe Chimpanzees in Uganda locked in vicious 'civil war', say researchers watgo - a WebAssembly Toolkit for Go linux/Documentation/process/coding-assistants.rst at master · torvalds/linux GitHub - callumlocke/json-formatter: Makes JSON easy to read. Founding Product Engineer at Bild AI | Y Combinator A compelling title that is cryptic enough to get you to take action on it GitHub - Keychron/Keychron-Keyboards-Hardware-Design: Industrial design files for Keychron keyboards and mice. 100+ models with CAD assets in STEP, DXF, DWG, and PDF. Source-available, with commercial use allowed for original compatible accessories within the license terms. [ANNOUNCE] WireGuardNT v0.11 and WireGuard for Windows v0.6 Released 1D-Chess Helium Is Hard to Replace Cooperative Vectors Introduction | Evolve Keeping a Postgres queue healthy — PlanetScale Our response to the Axios developer tool compromise Do Americans read print books, e-books or audiobooks more? The Zettelkasten Method in Obsidian: A Practical Setup Guide Artemis II Is Competency Porn and We Are Starving For It WeakC4 Flight Viz — Cockpit View A Mexican surveillance giant you’ve never heard of is now watching the U.S. border Surelock: Deadlock-Free Mutexes for Rust RISC-V 101 – what is it and what does it mean for Canonical? | Ubuntu The Problem That Built an Industry How Much Linear Memory Access Is Enough? | Solidean Investigating Split Locks on x86-64 Simplest hash functions Sybilproof reputation mechanisms (2005) [pdf] What is a property? How Complex is my Code? Static code analysis in Kotlin — tools overview Toffoli gates are all you need PGLite evangelism dcmake: a new CMake debugger UI Clojure on Fennel part one: Persistent Data Structures Fragments: April 2 Python Release Python install manager 26.1 The Life and Death of the Book Review - Liberties Bitcoin miners are losing $19,000 on every BTC produced as difficulty drops 7.8% God sleeps in the minerals Building slogbox Apple Silicon and Virtual Machines: Beating the 2 VM Limit Who was “Not Even Wrong” first? Pokemon Evolution Vs Darwinian Evolution The APL Programming Language Source Code
int a = 5; a = a++ + ++a; a = ?
2026-05-12 · via Hacker News

I've received the title riddle from furio and I found it interesting enough to pass it during the next few days to everyone that might be even remotely interested in C/C++ problems. The interesting thing here is the Undefined Behavior (UB), well... actually two UBs, thanks to which there are three possible correct answers: 11, 12 and 13.

Let's start with theoretical considerations on the possible answers and then get to empirical results (initially gathered by nism0, but later extended by readers from the Polish side of the mirror).

OK... so, which places are UB/unknown/compiler-dependent?

First UB
First, we don't know which a will get fetched first (by fetching I mean copying the value from memory to some internal register). There are two possibilities here:

Possibility 1. The first a will get fetched first, then the pre-increment will take place, and then the second a will be fetched (I'll skip the post-incrementation problem for now):
a = a + ++a;

Step 1. Fetch first a.
a = 5 + ++a; (a==5)

Step 2. Pre-increment a.
a = 5 + a;   (a==6)

Step 3. Fetch second a.
a = 5 + 6;   (a==6)

Step 4. Calculate the addition.
a = 11;


Possibility 2. The pre-increment will take place first and the result will be stored in memory, and then the fetching of a will take place.
a = a + ++a;

Step 1. Pre-increment a.
a = a + a;   (a==6)

Step 2 i 3. Fetching both a.
a = 6 + 6;   (a==6)

Step 4. Calculate the addition.
a = 12;


So, even with skipping the post-incrementation we get two different possibilities (11 and 12).

Second UB
The second UB is related to the post-incrementation and the potentially trivial line a = a++. As it occurs, there are also two possibilities here (I'll demonstrate them using int a = 5; a = a++; as an example).

Terminology:
a_mem - a still in memory (e.g. as a local variable somewhere on the stack)
a_copy - a previously fetched copy of a in some internal register

Possibility 1. Post-increment goes Missing In Action:
Initial setup: (a_mem == 5, a_copy == n/a)

Step 1. Fetching a.
a = 5++; (a_mem == 5, a_copy == 5)

Step 2. Post-increment on the variable (in memory).
a = 5;   (a_mem == 6, a_copy == 5)

Step 3. "Set" gets executed - a_copy is moved to a_mem.
(a_mem == 5, a_copy == n/a)


In the above case the result of post-incrementation went MIA - it got written to the memory but it was soon overwritten by another (not incremented) value. (Actually I've always thought that post-increment is always done after all operations finish so personally I would treat this behavior as a compiler bug.)

Possibility 2. Post-incrementation is deferred to the very end.
Initial setup: (a_mem == 5, a_copy == n/a)

Step 1. Fetching a.
a = 5++; (a_mem == 5, a_copy == 5)

Step 2. "Set" gets executed - a_copy is moved to a_mem.
(a_mem == 5, a_copy == n/a)

Step 3. Post-increment on the variable (in memory).
a++ (a_mem == 6, a_copy == n/a)


So, the post-increment is executed at the very end of the calculations and it does not get overwritten.

Summary of UBs
To sum up the two previously described UBs for the a = a++ + ++a equation we get:
Possibilities 1 i 1: 5+6 and the post-increment goes MIA, result: 11
Possibilities 2 i 1: 6+6 and the post-increment goes MIA, result: 12
Possibilities 1 i 2: 5+6 and the post-increment is deferred, result: 12
Possibilities 2 i 2: 6+6 and the post-increment is deferred, result: 13

Experimental results
Now for the empirical results (thx to nism0 for the initial tests and the initial table, and to nonek and qyon for spotting certain typos):

Code 1 Code 2 Code 3 Code 4 Code 5 Code 6
int a = 5;
a = a++ + a++;
int a = 5;
a = a++ + ++a
int a = 5;
a = ++a + a++;
int a = 5;
a = ++a + ++a;
int a = 5;
a = a++;
int a = 5;
a = a + ++a;

                           
Compiler/Lang Ver.Result 1 Result 2 Result 3 Result 4 Result 5 Result 6
gcc 2.9512 13 14 13 6 12
gcc 4.112 13 1413 6 12
gcc 4.212 13 1413 6 12
gcc 4.2.1 Apple 12 13 14 13 6 12
gcc 4.312 13 1413 6 12
gcc 4.3.3 12 13 13 14 6 12
gcc 4.4.4 12 13 13 14 6 12
gcc 4.6.0 (exp.) 12 13 14 13 6 12
gcc 4.5.1 MinGW64 12 13 13 14 6 12
tcc 0.9.25?? ?? ?? ?? 5 12
bcc 0.16.17?? ?? ?? ?? 5 12
Microsoft C/C++ 16.00.30319.01 (80x86)12 13 13 14 6 12
Embarcadero C++ 6.31 for Win32 12 13 13 14 6 12
Intel C++ 12.0.1.127 12 13 13 13 6 12
Keil C 9.02 11 12 12 13 6 12
SDCC 3.0.1 #6092 11 12 13 14 5 12
clang 2.8 11 12 12 13 5 11
clang 1.6 Apple 11 12 12 13 5 11
PHP 5.2.10 11 12 12 13 5 12
java 1.6.0_06 11 12 12 13 5 11
javac 1.4.2_12 11 12 12 13 5 11
java 1.6.0_21 11 12 12 13 5 11
javac 1.6.0_22 11 12 12 13 5 11
C# 2.0 11 12 12 13 5 11
C# 4.0 11 12 12 13 5 11
C# Mono 2.6.4 11 12 12 13 5 11
Borland Turbo C++ for DOS 2.01 12 13 13 14 6 12
HiSoft C for ZX Spectrum 1.3 11 12 12 13 5 12

Thanks for additional results to: Icewall, Krzysztof Kotowicz (PHP 5.2.10), mlen (2x clang, 2x gcc), none'a (2x Java), Keraj (2x Java), MDobak (SDCC & Keil C), garbaty lamer (3x C#, Turbo C++, HiSoft C), Xgrzyb90 (gcc 4.4.4), no_name (gcc 4.3.3), dikamilo (mingw64 4.5.1)

Garbaty lamer has also posted (in the comments on the Polish side of the mirror) a really cool screenshot from the HiSoft C for ZX spectrum (click to zoom):

HiSoft C for ZX Spectrum, screen by garbaty lamer

If you would like to test your compiler (posting back the results in the comments is really appreciated, especially from strange/uncommon compilers and other languages which support pre- / post- increments ;>) you can use the code (made by nism0) at the bottom of the post (see Appendix 3).

And that's that ;>

Appendix 1:
In the comments on the Polish side of the mirror Rolek has suggested to apply the same test to overloaded operators (see the comments on the Polish side for the code). Results (by Rolek from MSVC++ and me from g++):

Code 1 Code 2 Code 3 Code 4 Code 5 Code 6
int a = 5;
a = a++ + a++;
int a = 5;
a = a++ + ++a
int a = 5;
a = ++a + a++;
int a = 5;
a = ++a + ++a;
int a = 5;
a = a++;
int a = 5;
a = a + ++a;

     
Compiler/Lang. Ver.Result 1 Result  2 Result 3 Result 4 Result 5 Result 6
Microsoft C/C/++ (w/o overloading) 16.00.30319.01 12 13 13 14 6 12
Microsoft C/C/++ (with overloading) 16.00.30319.01 11 13 12 14 5 12
g++ (w/o overloading) 4.5.0 MinGW 12 13 13 14 6 12
g++ (with overloading) 4.5.0 MinGW 11 13 12 14 5 12

Also, krlm has posted a link to a good article about sequence points.

By the way...
If want to improve your binary file and protocol skills, check out the workshop I'll be running between April and June → Mastering Binary Files and Protocols: The Complete Journey

Appendix 2:
Garbaty lamer (again, on the Polish side of the mirror) has mentioned that in C# this riddle isn't actually a riddle - it's well defined behavior, see C# specification point §7.3:
Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Appendix 3:
Code for testing:
#include <stdio.h>

int main(void)
{
 int a = 5, b = 5, c = 5, d = 5, e = 5, f = 5;

 // test 1
 a = a++ + a++;
 printf("%i \n",a);

 // test 2
 b = b++ + ++b;
 printf("%i \n",b);

 // test 3
 c = ++c + c++;
 printf("%i \n",c);

 // test 4
 d = ++d + ++d;
 printf("%i \n",d);

 // test 5
 e = e++;
 printf("%i \n",e);

 // test 6
 f = f + ++f;
 printf("%i \n",f);

 // done
 return 0;
}

Appendix 4:
A comment from Cem Paya:
--start--
Similar to C#, this is also not a riddle for Java because Java defines
evaluation to be strictly left-to-right.
See section 15.7 here for some examples with side-effects as in your case:
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html
In C++ where it is undefined, the result can also depend on the
optimization level used during compilation, which can change the
number of times a value is referenced. eg the compiler expects "a" to
not change its value during the evaluation and may optimize other
occurences to the same one it fetched.

==end==