I have problems understanding when to use curly braces on If Else statements. I'm new to C++ and if you have any suggestions on books that will help please let me know. Using Visual Studio, I just started coding a little fill in the blank type story. Nothing sophisticated. It's not finished but please explain "do I need curly braces or not", why, and why when executed if you answer y to a boy, it ask the name and then gets stuck vs answering n to a boy, it ask the girls name and continues.
cout << "A horse or a unicorn?" << endl;
cin >> animal;
cout << "What is the name of your castle?" << endl;
cin >> castle;
cout << "Do you like kites or dragons?" << endl;
cin >> fly;
cout << "Once upon a time " << boy << " and " << girl << " " << " were playing at " << castle << " Castle." << boy << " was riding a " <<
animal << " when he saw " << girl << " playing in the castle." << endl;
cout << endl;
cout << girl << " saw " << boy << " riding his " << animal << " and decided she wanted to ride too. " << endl;
cout << boy << "'s " << pet << " named " << bestFriend << " was waiting for " << boy << " at the front of the castle." << endl;
cout << boy << " said, lets go fishing! but, " << girl << "said, I don't like to hurt fish." << boy << "said, ok, we'll fly a " <<
fly << "." << endl;
There would be only one statement executed after if/else. Curly brases are there to goup them so they would be executed at once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
if (x > 5)
x = 1;
y = 2;
//y=2 will be executed regardless of if statement
if (x > 5)
x = 1
y = 2
else
x = 2;
//Syntax error: else does not correspon to any if (because there were statements after it)
if (x > 5) {
x = 1;
y = 2;
} else
x = 2;
//Works fine
You may not use curly braces if you have only one statement in body of if/else in all other cases you should use them
There is a simple rule of thumb which applies to if/else, while, and for statements.
If there is only one line to execute, you do not need the curly braces.
1 2 3 4
if(ans == 'y')
cout << "Yay, you are a boy!" << endl;
else
cout << "Aww...." << endl;
If there are multiple lines to execute, the curly braces are required for the compiler to know what belongs with which statement.
1 2 3 4 5 6 7 8 9 10
if (ans == 'y')
{
cout << "Enter a boys name:" << endl;
cin >> boy;
}
else
{
cout << "Enter a girls name:" << endl;
cin >> girl; //If there were no braces, only the top would execute for "else"
} // and cin >> girl would execute regardless
Note that you can still use curly braces in both cases.
There's a tight battle between two different kinds of programmers: those that say to always use curly braces no matter what, those that prefer not using curly braces for single statements, and those that use a language like Python where you have to use good indentation or your code won't work.