The layout of braces

Joined
Sep 21, 2022
Messages
149
Reaction score
21
This is a typical example of the kind of code I see online.
Code:
  if (n == 0 || n == 1) {
    isPrime = 0;
  }
  else {
    for(i = 2; i <= n/2; ++i) {
      if(n % i == 0) {
        isPrime = 0;
        break;
      }
    }
  }
11 lines, and none of the open braces line up with closing braces.

I would do it like this...
Code:
  if (n == 0 || n == 1)
  { isPrime = 0;
  }
  else
  { for(i = 2; i <= n/2; ++i)
    { if(n % i == 0)
      { isPrime = 0;
        break;
  } } }
9 lines, exact same indenting, and every brace lines up.

Okay, I'm cheating on the last 3 braces, the order is wrong, but since they are the same character, I don't see a problem.
 
Joined
Jul 4, 2023
Messages
453
Reaction score
54
Check the code notation from C#
C#:
if (n == 0 || n == 1)
{
    isPrime = 0;
}
else
{
    for(i = 2; i <= n/2; ++i)
    {
        if(n % i == 0)
        {
            isPrime = 0;
            break;
        }
    }
}

IMO, writing code across multiple lines (e.g., splitting longer expressions into smaller parts or splitting blocks of code) is not a problem for the compiler and does not affect its performance. The compiler processes the code in such a way that whitespace characters (including newlines) are usually ignored unless they have a specific meaning in a given programming language (e.g., Python, where indentation matters).
 
Last edited:
Joined
Sep 21, 2022
Messages
149
Reaction score
21
When there's too much white space, I have to scroll the screen from the start of the loop/if to the end.

When the opening brace is more than a screen height from the closing brace, it makes a program hard to read, for a human.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,880
Messages
2,569,944
Members
46,246
Latest member
RosalieMar

Latest Threads

Top