Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to an if statement not followed by curly braces? [closed]

I am trying to understand this code snippet:

class Worker
{
    public bool DoThisJob(string job, int numberOfShifts)
    {
        if (!String.IsNullOrEmpty(currentJob))
            return false;
        for (int i = 0; i < jobsICanDo.Length; i++)
            if (jobsICanDo[i] == job)
            {
                currentJob = job;
                this.shiftsToWork = numberOfShifts;
                shiftsWorked = 0;
                return true;
            }
        return false;
    }
}

If this if statement has more then one line of code (including the for loop and the two returns), why doesn't it have curly braces?

like image 690
Elvis Gabriel Avatar asked May 01 '13 18:05

Elvis Gabriel


People also ask

What happens in a IF statement where there is no curly braces?

One-line statement Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces.

When can curly braces be omitted from an if statement?

If there is only one statement for the if condition, curly braces are optional but if there are a series of steps curly braces are mandatory. That being said, you always want to keep the option of adding more statements to an if condition later. It is more readable and reduces error or bugs.

Do you need curly brackets for if statements Java?

Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.


1 Answers

The code is equivalent to this:

class Worker
{
    public bool DoThisJob(string job, int numberOfShifts)
    {
        if (!String.IsNullOrEmpty(currentJob))
        {
            return false;
        }
        for (int i = 0; i < jobsICanDo.Length; i++)
        {
            if (jobsICanDo[i] == job)
            {
                currentJob = job;
                this.shiftsToWork = numberOfShifts;
                shiftsWorked = 0;
                return true;
            }
        }
        return false;
    }
}

Only the next statement is part of the if when there are no curly brackets. For the for loop, the if is the next statement, so everything is included with it.

like image 182
Cemafor Avatar answered Nov 15 '22 05:11

Cemafor