Reputation: 11
I am trying to make a game with 6 (counting the tutorial) missions in it. There are 6 bool variables, one for each mission. An if else comparator checks what variables are true, and sends you to the appropriate mission. The comparator works well enough if only 1 variable is true, but it if multiple variables are true than it does not. Here is a more simplified version of the code that presents the same error.
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool tutorial = true;
bool mission1 = true;
bool mission2 = true;
if (tutorial) {
printf("It does not work");
}
else if (tutorial, mission1) {
printf("It does work");
}
else {
printf("It doesn't work");
}
}
What should happen is the program prints out "It does work". Instead, it prints out the "It doesn't work". While I am aware that if I only wanted the program to print the middle option, I would put
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool tutorial = true;
bool mission1 = true;
bool mission2 = true;
if (tutorial, mission1) {
printf("It does not work");
}
}
That would prevent you from playing more than 1 mission as well. Please help.
Upvotes: 0
Views: 33
Reputation: 52632
The statement if (tutorial, mission1)
doesn't mean what you think it means. In this statement, tutorial, mission1
is a comma expression.
A comma expression is evaluated by evaluating what is left of the comma, throwing the result away, then evaluating what is right of the common.
So you evaluate tutorial
, throw away the result, then evaluate mission1
. The result is therefore the same as if you had just written if (mission1)
.
You may have meant if (tutorial && mission1)
or if (tutorial || mission1)
.
Upvotes: 1
Reputation: 28
I think you should use '&&' instead of ',' so the line would look like this:
if (tutorial && mission1){
This will check if both turorial and mission1 are set to true
Upvotes: 0
Reputation: 82026
To test that tutorial is completed, and mission 1 and 2 have not been completed, you will need to write:
if (tutorial && !mission1 && !mission2) {
printf("tutorial completed, mission 1 and 2 not completed");
}
Upvotes: 0