## 对于单行if或循环使用大括号(即{})的目的是什么？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (10)
• 关注 (0)
• 查看 (172)

```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++;```

``````void some_method(obj* a, obj* b)
{
if (a == nullptr)
{
throw null_ptr_error("a");
}
if (b == nullptr)
{
throw null_ptr_error("b");
}
if (a == b)
{
throw logic_error("Cannot do method on identical objects");
}
if (not a->precondition_met())
{
throw logic_error("Precondition for a not met");
}

a->do_something_with(b);
}
``````

``````void some_method(obj* a, obj* b)
{
if (a == nullptr)
throw null_ptr_error("a");
if (b == nullptr)
throw null_ptr_error("b");
if (a == b)
throw logic_error("Cannot do method on identical objects");
if (not a->precondition_met())
throw logic_error("Precondition for a not met");

a->do_something_with(b);
}
``````

``````matrix operator +(matrix const& a, matrix const& b) {
matrix c(a.w(), a.h());

for (auto i = 0; i < a.w(); ++i)
for (auto j = 0; j < a.h(); ++j)
c(i, j) = a(i, j) + b(i, j);

return c;
}
``````

``````matrix operator +(matrix const& a, matrix const& b) {
matrix c(a.w(), a.h());

for (auto i = 0; i < a.w(); ++i)
{
for (auto j = 0; j < a.h(); ++j)
{
c(i, j) = a(i, j) + b(i, j);
}
}

return c;
}
``````