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

princearthur791 picture princearthur791 · Sep 19, 2016 · Viewed 7.3k times · Source

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];
}

Answer

Pete Becker picture Pete Becker · Sep 19, 2016

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.