Shortest C++ Program

Have you ever thought about the shortest C++ program? In this article, we’ll look into the shortest C++ program.

C++ is a compiled language. Firstly, the compiler processes the source code files and produces object files. The linker will combine these object files to yield an executable program.

Let’s look into the smallest C++ program

int main() {}

This shortest program has a main() function it takes no arguments and does nothing. The curly brackets {} express the grouping in C++. Here it is used to start and end the main function.

As per the C++ standard, every C++ program must have exactly one global main function. The program starts executing this main() function.

The main function will return an int value. The program will return this value to the “system”. A non-zero value indicates the failure. Linux/Unix-based environments often make use of this returned value and Windows environments rarely use it.

Let’s compile and run this program

g++ -o shortest shortest_program.cpp

The program displays nothing, let us check the returned value.

echo $?

From the above output, we can see that it returns 0.

Let’s disassemble this program and see the instructions. Yes, it is not that small :).

g++ -S -o shortest.s shortest_program.cpp
	.file	"shortest_program.cpp"
	.globl	main
	.type	main, @function
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	.size	main, .-main
	.ident	"GCC: (Ubuntu 11.2.0-7ubuntu2) 11.2.0"
	.section	.note.GNU-stack,"",@progbits
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
	.string	"GNU"
	.align 8
	.long	0xc0000002
	.long	3f - 2f
	.long	0x3
	.align 8

That’s all about the shortest C++ program.

Leave a Comment