Hi so basically my question is what does a for loop without any curly braces around it do? So from what I know, that during an if-statement only the first line of the code is executed. So in a for loop how does it work? I don't really understand the concept of a loop without the braces and with the braces. I guess an explanation with a piece of code would help. This is in C by the way. Here's a code I've been looking at as a reference.
int main(int argc, char* argv[])
{
int i;
int count = 0;
for (i = 0; i < 5; i++)
count++;
printf("The value of count is: %d\n", count);
return 0;
}
In this case, I see that there is no curly braces, so I am assuming that it will just keep iterating the first statement until i < 5 and once i is not less than 5 it doesn't do anything, but when I tested the code I get that it also ends up printing the printf statement. I thought that a loop without curly braces executed only the first line of code? Or am I missing something here.
If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.
If there is no braces, only one statement is inside the loop. In your example above, the statement is an empty statement (noted with a lone semicolon). Your example above is equivalent to: while (watch.
So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.
You don't actually need the curly braces around the for loop body. If you omit the curly braces, then only the first Java statement after the for loop statement is executed. Here is an example: for(int i = 0; i < 10; i++) System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With