Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of adding spacings between operators? [closed]

Tags:

c++

c

spacing

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.

like image 829
user0002128 Avatar asked Dec 12 '12 08:12

user0002128


3 Answers

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")

like image 181
Lei Mou Avatar answered Nov 21 '22 19:11

Lei Mou


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.

like image 45
Luchian Grigore Avatar answered Nov 21 '22 18:11

Luchian Grigore


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;
}
like image 26
Luca Davanzo Avatar answered Nov 21 '22 20:11

Luca Davanzo