if block without curly braces makes subsequent else if nested
The behaviour isn’t actually different, it’s entirely consistent: the whole inner if
block – including else if
– is considered as one block.
This is a classical ambiguity in parsing, known as the “dangling-else
problem”: there are two valid ways of parsing this when the grammar is written down in the normal BNF:
Either the trailing else
is part of the outer block, or of the inner block.
Most languages resolve the ambiguity by (arbitrarily) deciding that blocks are matched greedily by the parser – i.e. the else
[if
] is assigned to the closest if
.
Why an IF block is allowed inside another IF that doesn't have curly brackets in JAVA
Normally in JAVA if an IF statement doesn't have curly brackets can have only one line that is executed when IF condition is met,
Correction. An if
statement without braces can have only one statement that is executed when the condition is met. And the syntax of if
goes something like
if (<condition>) <statement>; [else <statement>;]
That is, if there's an else
, it's part of the if
. It's all one statement.
The reason there's no error is because there's no ambiguity here. (Well, not to the compiler, anyway.) Since the else
is part of the if
, it goes with the closest if
. So with proper indenting, you have
if (true)
if (true)
System.out.println("true");
else
System.out.println("false");
Is it a bad practice to use an if-statement without curly braces?
The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.
Maintainability-wise, it's always smarter to use the second form.
EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html
How to check/detect an 'if' clause without curly braces?
Just invert the logic, and put the active part in the else
branch:
#define DEBUG if( !getDebugmode( DEBUG_LEVEL_DEBUG ) ) \
; \
else \
GET_DEBUG_DST( DEBUG_LEVEL_DEBUG ).nospace() \
<< DEBUG_PREFIX << __PRETTY_FUNCTION__
Since there is a matching else
for the if
, it can't pick up
any additional else
.
PHP - If/else, for, foreach, while - without curly braces?
When you omit the braces it will only treat the next statement as body of the condition.
if ($x) echo 'foo';
is the same as
if ($x) { echo 'foo'; }
but remember that
if ($x)
echo 'foo';
echo 'bar';
will always print "bar"
Internally it's the other way around: if
will only look at the next expression, but PHP treats everything in {}
as a single "grouped" expression.
Same for the other control statements (foreach
, and so on)
Curly braces in if-else blocks
For example:
if (something)
if (something else)
...
else (blah blah)
Is the same that:
if (something)
{
if (something else)
...
else (blah blah)
}
In this case, yes, they're the same, but the former is harder to read than the latter. I recommend using braces always, even for blocks of code made of a single line.
What does a 'for' loop without curly braces do?
Without curly braces, only the first statement following the loop definition is considered to belong to the loop body.
Notice that in your example, printf
is only called once. Though its indentation matches the previous line, that's a red herring – C doesn't care. What it says to me is that whoever wrote the code probably forgot the braces, and intended the printf
statement to be part of the loop body.
The only time I would leave out the curly braces is when writing a one-line if
statement:
if (condition) statement;
do_something_else();
Here, there's no indentation to introduce ambiguity about whether the statement on the second line is actually supposed to belong to the body of the if
. You would likely be more confident when reading this that it's working as intended.
Nested if-statements without brackets
Yes. The if statement applies to the next statement after it - which happens to be another if in this case.
nested loop without curly braces
This code:
for (unsigned int i=1;i<=counter;++i)
{ printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j)
sum1 =sum1+j;// 1 iteration sum=1;
printf("The i is %d and the sum is %d\n\n",i,sum1);}
is equivalent to:
for (unsigned int i=1;i<=counter;++i) {
printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j) {
sum1 =sum1+j;// 1 iteration sum=1;
}
printf("The i is %d and the sum is %d\n\n",i,sum1);
}
This is because in for-loop
s without braces, only the very next line is included in the loop.
Now in the first iteration, you will get:
"The i is 1 and the sum is 0"
"The i is 1 and the sum is 0"
"The i is 1 and the sum is 1" //Enters inner for-loop
Second:
"The i is 2 and the sum is 1" //Hasn't reset yet
"The i is 2 and the sum is 0" //Reset
"The i is 2 and the sum is 3" //Sum was 0, then added 1 when j was 1,
//then added 2 when j was 2
Now, the reason you can't print j, is because your printf
statements are all outside of your inner for-loop
, so j
is not defined :)
Related Topics
Bring Window to Front -> Raise(),Show(),Activatewindow() Don't Work
Stopping an Infinite Loop in C++ When Key Is Pressed
How to Sort C++ Array in Asc and Desc Mode
Template Specialization for Multiple Types
Getopt Fails to Detect Missing Argument for Option
How to Add Playable(Such as Wav,Wmv) Header with Pcm Data/Buffer in iOS
Do You Prefer Explicit Namespaces or 'Using' in C++
How to Construct or Return the Underlying Deque from a Stack
Best C++ Development Environment in Linux
C and C++ Functions Without a Return Statement
C++ Makefile on Linux with Multiple *.Cpp Files
Nat-Traversal Implementation for P2P Connection
What Is the Significance of 'Strongly Happens Before' Compared to '(Simply) Happens Before'
What's the Difference Between C and C++
Std::Lower_Bound Slower for Std::Vector Than Std::Map::Find
Instantiating Classes by Name with Factory Pattern
Why Does My Program Run Way Faster When I Enable Profiling
Why Is '"Literal"' Encouraged to Decay to 'Const Char*' in C++ Argument Type Match