#include // The following program does not compile. // // Identify why it does not compile, and then fix // the problem so that the program prints the // absolute value of the integer entered by the user. // // Try to find the bug before compiling the program. // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; if ( n >= 0 ) { int result{ n }; } else { int result{ -n }; } std::cout << "The absolute value of " << n << " is " << result << std::endl; return 0; } // Explanation: // // The problem is that 'result' is declared separately // inside each of the two blocks of the if statement: // // if ( n >= 0 ) { // int result{ n }; // } else { // int result{ -n }; // } // // These are actually two different local variables // that happen to have the same name. // // The first 'result' exists only within the block // following the 'if', while the second 'result' // exists only within the block following the 'else'. // // Consequently, neither variable is in scope when // the program later tries to execute // // std::cout << ... << result << std::endl; // // The solution is to declare 'result' before the // if statement. It will then remain in scope after // the if statement has finished executing. // // The appropriate value can then be assigned to // 'result' within each branch. // Here is one solution: /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; int result{}; if ( n >= 0 ) { result = n; } else { result = -n; } std::cout << "The absolute value of " << n << " is " << result << std::endl; return 0; } */