Let me state flat out what follows is part of MY formatting style; others can and will likely disagree.
So when you're writing code you physically have to press the space bar 3 times when going on a new line? |
No.
The VS formatting setup lets you set the tab indent size, and whether it uses tabs as tabs or converts tabs to spaces.
I hit tab and the VS editor puts in 3 spaces.
If I copy and paste code that uses tabs VS changes the tabs to spaces.
If I copy and paste code that is indented less than 3 spaces, or more than 3, it uses 3 spaces for the indent.
Your first example is K&R style formatting, your second is Allman style.
Your third example is not a style that is officially named that I can find.
VS lets you set how brace control blocks are style formatted.
https://en.wikipedia.org/wiki/Indent_style#Brace_placement_in_compound_statements
That same page also talks about the religious wars over tabs vs. spaces
I generally follow Allman style, with a mandatory braces variation.
https://en.wikipedia.org/wiki/Indent_style#Variant:_mandatory_braces
Here's a code snippet that "misuses" whitespace without control braces, to a casual reader the actual execution flow is obscured:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
int main()
{
std::cout << "Enter a number less than 10 or greater than 100: ";
int x { };
std::cin >> x;
std::cout << '\n';
if (x >= 10)
if (x > 100)
std::cout << "More than 100, Thanks!\n";
else // not the else intended!
std::cout << "Less than 10, Thanks!\n";
}
|
The
else statement belongs to the second
if, not the first. If I were to paste that code into VS, it would automatically be properly formatted. Indenting the
else clause to its proper place
I personally go one step further, with "mandatory" braces:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
int main()
{
std::cout << "Enter a number less than 10 or greater than 100: ";
int x { };
std::cin >> x;
std::cout << '\n';
if (x >= 10)
{
if (x > 100)
{
std::cout << "More than 100, Thanks!\n";
}
}
else // fixed!
{
std::cout << "Less than 10, Thanks!\n";
}
}
|
Now it is very obvious where the
else chains up. By brace usage and indentation.
For me readability is improved for what is intended.
Should I decide later to add one or more statements to the
else clause they will be properly contained since the brace control block is already there.
I set VS to do brace completion, if I type an opening brace the editor automatically adds the closing brace.
The bottom line is IMO:
No matter what formatting style one uses, use it as consistently as possible for readability.
If on occasion using the third style you posted doesn't decrease readability, then I use it.