General Category > Implementation Details

Code formatting of C2's c++

<< < (2/2)

lerno:
I think any else without { } is bad, so:


--- Code: ---if (x) func1();
else func2();

--- End code ---

Would also be a no-go from my perspective, to the point that I would consider changing grammar so that if-else WOULD NEED to be written with blocks.

So:

Good

--- Code: ---if (foo) bar();

if (foo) {
  bar();
} else {
  baz();
}

if (foo) {
  bar();
} else if (foo2) {
  baz();
}

--- End code ---

Accepted by C2, but not in C2 C++ formatting

--- Code: ---if (foo)
  bar();

--- End code ---

Not accepted by C2, not allowed in C2's C++ formatting

--- Code: ---if (foo) bar();
else baz();

if (foo) {
  bar();
} else baz();

if (foo) bar();
else {
  baz();
}

--- End code ---

bas:
We could have the analyser check that if either the if or else body has braces, that they both have. If not, just give an error.

I wouldn't really want to prevent developers from writing a short if/else and always require braces. It's a matter of style at
some point. On the todo-list is a clang-format like style program that styles C2 code. That tool could be used to check/fix
this as well. That removes it from the language and puts it in the style part...

lerno:
I'm just in favour for making the dangling else unambiguous always. Code like


--- Code: ---if (foo) if (bar) baz(); else foobar();

--- End code ---


... should never ever be written. :D Requiring braces for if-else prevents ambiguous code.

Someone might write:

--- Code: ---if (foo)
  if (bar) baz();
else
  foobar();

--- End code ---


But what they get is:

--- Code: ---if (foo)
  if (bar)
    baz();
  else
    foobar();

--- End code ---


This is never ambiguous:

--- Code: ---if (foo) {
  if (bar) baz();
} else {
  foobar();
}
// or
if (foo)
  if (bar) {
   baz();
  } else {
    foobar();
  }

--- End code ---


if we allow if (foo) { ... } else ... / if (goo) ... else { ... } (that is, braces is needed for at least one part), then that would solve ambiguity as well.

We would be allowing if ( ... ) ...; so we're not locking down short ifs. Just preventing ambiguous if-else constructs.

bas:
You can't protect against stupidity  ;).
If people want to write that code, let them, but don't burden good/normal developers by those restrictions..

lerno:
Oh, it's not about stupidity, it's about grammar ambiguity.

Navigation

[0] Message Index

[*] Previous page

Go to full version