C++

Asked • 05/31/19

What's the purpose of using braces (i.e. {}) for a single-line if or loop?

I'm reading some lecture notes of my C++ lecturer and he wrote the following: > 1. Use Indentation // OK > 2. Never rely on operator precedence - Always use parentheses // OK > 3. Always use a { } block - even for a single line // **not OK**, why ??? > 4. Const object on left side of comparison // OK > 5. Use unsigned for variables that are >= 0 // nice trick > 6. Set Pointer to NULL after deletion - Double delete protection // not bad The 3rd technique is not clear to me: what would I gain by placing one line in a `{ ... }`? For example, take this weird code:  int j = 0;  for (int i = 0 ; i < 100 ; ++i)  {   if (i % 2 == 0)   {    j++;   }  } and replace it with:  int j = 0;  for (int i = 0 ; i < 100 ; ++i)   if (i % 2 == 0)    j++; What's the benefit of using the 1st version?

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.