Hi everybody, new to the forums. I'm relatively new to programming, and I'm trying to teach myself as a hobby. I'm using Teach Yourself C++ in 21 Days, and I'm currently on pointers and references.
I'm struggling with this code. I feel like I understand the result, but I don't understand why it does what it does . . .
Code:
#include <iostream>
using namespace std;
short Factor (int n, int* pSquared, int* pCubed);
int main()
{
int number, squared, cubed;
short error;
cout << "Enter a number (0 - 20): ";
cin >> number;
error = Factor(number, &squared, &cubed);
cout << "Error: " << error;
if (!error)
{
cout << "number: " << number << endl;
cout << "square: " << squared << endl;
cout << "cubed: " << cubed << endl;
}
else
cout << "Error encountered!!" << endl; */
return 0;
}
short Factor(int n, int *pSquared, int *pCubed)
{
short Value = 0;
if (n > 20)
Value = 1;
else
{
*pSquared = n*n;
*pCubed = n*n*n;
Value = 0;
}
return Value;
}
(This code is from page 269, "SAMS Teach Yourself C++ in 21 Days by Liberty and Jones)
What's confusing me is the if statement !error. I read this as "if not 1" if the user input is greater than 20, or "not 0" if it is less than 20. But the function returns either 1 or 0 as the value for error, so either way the result is "not error." Shouldn't the else statement run anyway? I know 0 means the function ran as intended. But it seems to me the if statement should be "error != 1". I'm sure this is an obvious thing, but I'm definitely missing something. Thanks for any help!