Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I don't need brackets for loop and if statement

I don't understand why I don't need brackets in this case

for (int i = 0; i < 10; i++) 
    if (num[i] < min) 
        min = num[i];

And why I need brackets in this case

int num[10], min;
for (int i = 0; i < 10; i++) {
        cout << "enter 10 numbers" << endl;
        cin >> num[i];
}
like image 224
princearthur791 Avatar asked Sep 19 '16 18:09

princearthur791


People also ask

Do you need if statement in for loop?

Create a for- loop to repeatedly execute statements a fixed number of times. Create a while- loop to execute commands as long as a certain condition is met. Use if-else constructions to change the order of execution.

Can we use if statement without curly braces?

Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.

DO IF statements need brackets in C++?

In C, C++ and Java, if you add another statement to the then clause of an if-then: if (condition) statement1();


2 Answers

Both the for and the if have to be followed by a "statement". A "statement" can be a simple statement, like min = num[i];, a more complicated one like if (num[i] < min) min = num[i]; or it can be a compound statement (i.e., zero or more simple statements enclosed in curly braces), like { std::cout << "enter 10 numbers\n"; std::cin >> num[i]; }

Some people think that cluttering simple statements with syntactically redundant curly braces is good style. Others don't.

like image 95
Pete Becker Avatar answered Oct 16 '22 04:10

Pete Becker


Because you don't.

They are optional. That is just how it is.

If you don't use braces to group multiple statements into one, then only the first statement following the for or if preamble is considered part of that construct. (But this rule is transitive, so your assignment is part of your if is part of your for!)

It is important to note that indentation has no effect.

Many people believe[citation needed] that you should always use braces, for clarity.

like image 26
Lightness Races in Orbit Avatar answered Oct 16 '22 04:10

Lightness Races in Orbit