#include <cstdlib>
#include <iostream>
usingnamespace std;
#include <cassert>
int main()
{
int year;
cout << " Please enter your year of birth: " << endl;
cin >> year;
assert (year = 2018); //someone born this year can't vote
assert (year > 2018); //someone born last year cant vote
assert (year > 2000);// someone below 18 can't vote
if ( year < 2001)
{
cout << " your are legally allowed to vote" << endl;
}
return 0;
}
Presumably you meant to say year == 2018. A single equals sign means assignment, not a test for equality. But the tests don't make sense anyway. This alone would do it:
assert(year > 2000);
The program doesn't make a lot of sense anyway. Do you really know what an assert does? It's a debugging macro. You probably just want an if, like you have already.
the assert should throw an exception if the following happens
- the year of birth is the same as the current year
- the year of birth is greater than the current year
- if the persons year of birth is more than 2000 and that means they are below 18
from what i understand the assert function should be used to validate input. if any of the above conditions are met then an exception should be thrown and the program does not proceed.
That is an uncommon use of asserts. As tpb says, they're generally not used that way. If those are your instructions, then of course follow the instructions, but they will only take effect in debug builds.
In release builds, asserts generally do nothing.
asserts do not throw an exception; they call std::abort
In summary:
from what i understand the assert function should be used to validate input.
Based on what I said above, no, they should not. Remember, asserts don't even exist in the release build. Why would you only validate input in the debug build? Surely you should also validate input in the release build?
if any of the above conditions are met then an exception should be thrown
Assertions are normally used to check for conditions that should never happen. I.e. logical errors caused by mistakes of the programmer. Errors caused by the user are normally handled some other way because, as Repeater said, assertions can be turned off, and the way they show errors isn't very user friendly.