Why do you have to cover it with a block when you repeat only one line of code?

Asked 1 years ago, Updated 1 years ago, 72 views

I'm taking a C++ course and in the textbook,

It says so. Other than that, you can understand it for readability or safety reasons I don't understand to use {} even when writing a line.

I think the source code 1 looks dirty What's the advantage of using it like that?

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;

c c++ coding-style curly-brace defensive-programming

2022-09-21 17:42

1 Answers

Let me illustrate with an example.

Let's add the variable j to source code 2 and change it to a code that increases j and i together.

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
        i++;

At Python, it will work as intended. But in c++, it runs like the code below.

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
i++;

Here are some common situations in which code is tested:

if (condition)
  do_something();
else
  do_something_else();
must_always_do_this();

If you annotate do_something_else() in else in the same code,

if (condition)
  do_something();
else
  //do_something_else();
must_always_do_this();

must_always_do_this() that can be compiled but should always be called enters else statement The program does not run as intended.

Of course, these situations are minor mistakes that won't happen if you pay a little attention Have you all experienced this before?

This is because c++ determines the block by {} This is caused by the difference between the blocks that you see and expect.

It's easier to follow the block if you write {} like source code 1 Even if you write one line, you should specify {}.

But I don't think you need to always follow that textbook. If you're going to change the code later or if you're using it with someone else, it's better to tie it up with {} Wouldn't it not be necessary to do that in a simple conditional test?


2022-09-21 17:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.