Solved

when are these needed {}

Posted on 2012-12-20
1
196 Views
Last Modified: 2012-12-20
if (Project.ProjectID == 0) PID = 1; else PID = 2;

Why does this not have to have the brackets. When are they optional

if (Project.ProjectID == 0)
{
PID = 1;
}
else
{
 PID = 2;
}
0
Comment
Question by:Eamon
1 Comment
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 38710073
Brackets are optional if the body of your if (or else if, or else) consists of only one line. In your example, they would be optional, meaning this is exactly equivalent:

if (Project.ProjectID == 0) 
    PID = 1;
else 
    PID = 2;

Open in new window


The problem with using this approach is that it is easy to overlook the fact that this is only valid for single-ling bodies. For example, this would be a compilation error:

if (Project.ProjectID == 0) 
    PID = 1;
    PID = 2;
else 
    PID = 2;

Open in new window


The reason this fails is because the PID = 1; is the body of the if. Then you have a separate line of code in PID = 2;. Then you have an else that does not have an associated if (because of the intermediate PID = 2; line.

In your first example, this is actually very difficult to read. It would be easy for someone to completely overlook the else if they were scanning over your code.
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question