Skip to main content

Command Palette

Search for a command to run...

How to Return a Custom Exit Code in Your Program

Published
1 min read

Another simple program involves returning a specific number instead of the usual 0. Here is the equivalent code in C++ for that:

#include <iostream>
using namespace std;

int main() {
    return 5;
}

The same code we used to return 0 in assembly will look like this when we return 5.

.global _start

.section .text
_start:
  mov $60, %rax
  mov $5, %rdi
  syscall

The major change here is that everything else remains the same, but there is a difference in the code compared to the previous version where we returned 0.

mov $5, %rdi

Here, we are moving 5 into rdi instead of doing what we did in the previous code, which was to use xor with the same register. This is usually done because it saves time and is highly optimized for returning 0, as that operation is needed more often.

xor %rdi, %rdi

This is the assembly code for returning 5 instead of 0. Other than this change, everything else remains the same.