All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

Why x86 compilers prefer xor over sub for zeroing registers: encoding efficiency and convention

By

ingve

1mo ago· 4 min readenInsight

Summary

Matt Godbolt's article explores why x86 compilers prefer the `xor eax, eax` instruction over `sub eax, eax` for zeroing out registers. The key reason is that `xor` is the most compact encoding on x86, being several bytes shorter than `mov eax, 0` since it avoids encoding a four-byte constant. The article notes that while both `xor` and `sub` could theoretically work, `xor` became the standard idiom due to historical convention, encoding efficiency, and compiler optimization preferences.

Key quotes

· 3 pulled
The answer is that it is the most compact way to set a register to zero on x86.
In particular, it is several bytes shorter than the more obvious mov eax, 0 since it avoids having to encode the four-byte constant.
The x86 architecture does not have a dedicated zero register, so if you need to zero out a register, you'll have to do it ab initio.
Snippet from the RSS feed
Somehow xor became the most popular version.

You might also wanna read