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 i
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 the for-loop does not have braces, it will execute the next statement. The syntax is essentially
for (<initialization>;<condition>;<increment>) <statement>;
The "statement" part can be anything. It could be a simple count++; or it could be an 'if'/'if-else' statement, it could even be another for-loop without the braces!
So in this case, the code is similar to:
for (i = 0; i < 5; i++) {
count++;
}
printf("The value of count is: %d\n", count);