I basically learnt C/C++ programming by myself, so I don't know much about good programming habit. One thing always make me wonder is why people always like to add spacing between operators in their codes like:
if(x > 0)
instead of
if(x>0)
Are there any particular reasons for that? We know the compiler simply ignores such spacings, and I don't think the latter expression is less readable.
Sometimes space is necessary because the maximal munch priciple of the C/C++ lexer. Consider x
and y
are both pointers to int, expression
*x/*y
is illegal because the lexer will treat /*
as comment. So in this case, a space is necessary:
*x / *y
(From book "Expert C Programming")
I doubt that always happen, as you claim. In general, when working on a large project, there are conventions in place on whether spaces are to be added or not.
I'd apply spaces on a case-by-case basis:
a+b+c+d
is more readable, IMO, than
a + b + c + d
however
a+b*c+d
is less readable than
a + b*c + d
I'd say follow the conventions first, and afterwards think about readability. Consistent code is more beautiful.
It's simply good manner. You can write your code as you want, but this is a kind of "standard" way.
Also makes the code more readable.
Two examples to make you understand.
1) Space less
if(x<0.3&&y>2||!std::rand(x-y)&&!condition){
std::cout<<++x?0:1<<std::endln;
}
2) With good formatting:
if (x < 0.3 && y > 2 || !std::rand(x - y) && !condition) {
std::cout << ++x ? 0 : 1 << std::endln;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With