Home > OS >  PSET 1 Credit CS50
PSET 1 Credit CS50

Time:09-19

I'm working on credit PSET from CS50 and I managed to do most of the code but when I reach the conditions to check if the card is Valid it gives me this error when I try to compile it. use of logical '||' with constant operand, use '|' for a Bitwise operation. This is the part that breaks in my code.

   if (counter > 12 && counter < 17) // check first condition
   {
       if (sum % 10 == 0) // check 2nd condition
       {
           if (number != (4 || 34 || 37 || 51 || 52 || 53 || 54 || 55))
           {
               do
               {
                   testnumber4 /= 10;
               }
               while (testnumber4 != (4 || 34 || 37 || 51 || 52 || 53 || 54 || 55));
               if (testnumber4 == 4)
               {
                   printf("VISA\n");
               }
               else if (testnumber4 == (34 || 37))
               {
                   printf("AMEX\n");
               }
               else if (testnumber4 == (51 || 52 || 53 || 54 || 55))
               {
                   printf("MASTERCARD\n");
               }
               else
               {
                   printf("INVALID\n");
               }
           }
           else
           {
               printf("INVALID\n");
           }
       }
       else
       {
           printf("INVALID\n");
       }
   }
   else
   {
       printf("INVALID\n");
   }

CodePudding user response:

Your code

if (number != (4 || 34 || 37 || 51 || 52 || 53 || 54 || 55))

Is an attempt to phrase your logic like you speak it, "number is not 4 or 34...",
or more precisely "number is not anything from the list of 4, 34, ...".

Even with spoken language, this is misunderstandable, but humans usually can tell from context what you mean.
Compiler however are stupid. So you need to be extremely un-misunderstandable. You need to spell it out in extreme detail. You would have to phrase "number is not 4, and number is not 34, and number is not ....".

In C that looks like this

if ( (number !=  4)  &&
     (number != 34)  &&
     (number != 37)  &&
     (number != 51)  &&
     (number != 52)  &&
     (number != 53)  &&
     (number != 54)  &&
     (number != 55) 
   )

The error you get is explained by how confused the compiler gets trying but failing to understand your logic.
It thinks "take all those numbers and logically or them; hmmm, they are all non-zero; so the result is like 'true or true or true'; hmmm, that does not make sense, maybe you want to binary-or them? That would at least give a somewhat interesting value.".

  • Related