Gaarsin Gaarsin - 6 days ago 6
C Question

Slot Machine Game In C - Printing Reels Issue

I'm trying to create a small slot-machine game that has three reels and four possible symbols for each reel (bell, orange, cherry, and horse).

I started by generating a random value between 1-4 and now I'm trying to get the first reel to print out the text associated with the generated values.

Here is the code, I hope someone can help and point out why it doesn't work and how I can fix it. From the code below I was expecting the program to print out 3 different pieces of text that were associated with the generated numbers but instead "Cherry" prints out three times.

// Generates 3 different random values between 1-4 and stores them within the slotVal array.
int slotVal[3], counter;
srand(time(NULL));

for (counter = 0; counter < 3; counter++) {
slotVal[counter] = rand() % 4 + 1;
}

// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
if (slotVal[counter] = 1) {
printf("Cherry");
}

else if (slotVal[counter] = 2) {
printf("Bell");
}

else if (slotVal[counter] = 3) {
printf("Orange");
}
else
printf("Horseshoe");
}

M.M M.M
Answer

Your if statements are wrong, you are assigning(=) not comparing(==):

// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
    if (slotVal[counter] == 1) {
       printf("Cherry");
    } else if (slotVal[counter] == 2) {
        printf("Bell");
    } else if (slotVal[counter] == 3) {
        printf("Orange");
    } else {
        printf("Horseshoe");
    }
}

If you do if(something = 1) the condition evaluated will be the 1 because the assignment operator returns the assigned variable. Since 1 evaluates to true, your first condition would be met and the other else blocks would be ignored.


Some useful tips to avoid this particular error are:

  • Do if(1 == variable) instead of if(variable == 1), because the first raises a compilation (if you only use one = sign) error and the second doesn't;
  • Define a name for the comparison, for example: #define EQUALS == which will allow you to do if(variable EQUALS 10)
Comments