hello, i recently was asked to help a friend with a c++ error he had after he attempted something in a book. am not a pro on c++ myself, were both still learning it
basically i read over it but could not understand what the problem was so spent a few hours trying to understand it before finally finding what was causing the logic error. ( it always compiled fine)
this is the original code, it basically draws a square.
Code:
#include <iostream>
int main(){
const int rows = 5;
const int cols = 5;
std::cout << std::endl;
for(int x=0; x!=rows; ++x){
int y=0;
while(y!=cols){
if(x == 0 || x == rows-1 ||
y == 0|| y == cols-1) { << bracer i mean this {
/* will result in constant
******* forever when compiled.
if the braces following the if
and else are removed e.g {}.
it works correctly */
std::cout << "*";
} // << bracer i mean this
else{ << bracer i mean this
std::cout << " ";
++y;
} // << by bracer i mean these
} // end while
std::cout << std::endl;
} // end for
return 0;
}
i have commented what and where the error occurs above. basically by using bracers for his if else statement the flow of the programme my friend had made it work incorrectly which i didnt know was possible.
i have been told adding bracers to an if else statement is optional and including or not including them changes very little in a program. however in the above programme it can cause it to either work right or not at all.
can someone please clarify ? what are the braces doing to cause the error?
thank you in advance