Question:
I am starting to learn C++. In the course of studying, I noticed a certain thing, namely the ability to not put curly braces ( {}
) to limit, for example, the loop body, branching, etc. At the same time, there are no problems during compilation, and the code without curly braces works just as correctly as the code with them.
I would like to know how correct this is from the point of view of code aesthetics and which option to use and whether there is at least some difference at all.
For example, here is the code with curly braces :
#include <iostream>
using namespace std;
int main() {
while (true)
{
cout << "Hello, world" << endl;
}
}
Without curly braces :
#include <iostream>
using namespace std;
int main() {
while (true)
cout << "Hello, world" << endl;
}
Answer:
It's not a question of aesthetics. If it is accepted in the team this way or that – do as in the team. If you work alone – as you wish. But keep in mind that without a parenthesis, then, in a hurry, you can add another line and forget about the parentheses. And it's good if it's something like
if (a > b)
cout << "OK";
else
cout << "Fail";
turned into
if (a > b)
с = a - b;
cout << "OK";
else
cout << "Fail";
where the compiler will help out … And if
while (true)
cout << "Hello, world" << endl;
will turn into
while (true)
n++;
cout << "Hello, world" << endl;
Whereas? Therefore, I would recommend (not imposing :)) as a beginner to put brackets, just for my own peace of mind.
Over time, you will decide for yourself which is more convenient for you.
And once again – when working in a team with an established coding style – stick to the style of the team.