DEV Community

Ben Santora
Ben Santora

Posted on

K&R vs Allman: Code Formatting Styles

Code formatting helps make programs more readable and easier to maintain. Two common styles are K&R (Kernighan & Ritchie) and Allman.

In K&R style, the opening curly brace { appears on the same line as the statement (e.g., if or else). This keeps the code compact, using fewer lines.

K&R

Image description

Allman style places the opening brace on a new line. Though it takes more vertical space, it makes it easier to see where each code block starts and ends, improving readability for some.

Allman

Image description

The choice between K&R and Allman often depends on personal or team preferences. I learned using the K&R method and it seems much more common. But I found when trying to learn nested code blocks like the if-else-if-else statements in the C program shown above, that the Allman style helped me better see what was happening - ie - when I'm LEARNING a program, trying to understand the algorithm, etc. - I'll often write out the code in the Allman format - I think it really does help, especially for beginners. You can always default back to K&R once you've grasped what's going on.

Ben Santora - October 2024

Top comments (0)