Thread: infinite loop

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    10

    infinite loop

    Hi:

    Could someone please help?

    I want to check if input valid or not. But my code doesn't stop as expected.

    Code:
    void validateSex(char sex) {
       if ( sex != 'M' || sex != 'F') {
         printf("Input Error: Invalid \n");
    
         do {
           printf("Enter your sex (M or F): ");
           scanf("%c", &sex);
         }while (sex !='M' || sex!='F');
       }; /* End if */
    }
    whats wrong with it?

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > while (sex !='M' || sex!='F')
    sex = M, so sex != 'F' is true, so round the loop you go.
    sex = F, so sex != 'M' is true, so round the loop you go.

    Perhaps && instead.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    > if ( sex != 'M' || sex != 'F') {
    That's always true.

  4. #4
    Hacker MeTh0Dz's Avatar
    Join Date
    Oct 2008
    Posts
    111
    Your current implementation is using an unnecessary do loop and if statement. If you are going to evaluate if it is true or false before the do loop anyways, there is no reason to even use it. Just use a while loop instead.

    Code:
    void validateSex(char sex) {
    	while (sex !='M' && sex !='F') {
    		printf("Enter your sex (M or F): ");
    		scanf("%c", &sex);
    	}
    }

  5. #5
    Registered User
    Join Date
    Nov 2003
    Posts
    10
    Thanks for your help.

    Problem solved.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-14-2009, 11:24 PM
  2. Cosine fucntion and infinite loop.
    By youareafever in forum C Programming
    Replies: 2
    Last Post: 11-07-2008, 04:45 AM
  3. Infinite Loop with GetAsyncKeyState
    By guitarist809 in forum Windows Programming
    Replies: 1
    Last Post: 04-18-2008, 12:09 PM
  4. Switch statement = infinite loop
    By Lucid003 in forum C++ Programming
    Replies: 10
    Last Post: 10-10-2005, 12:46 AM
  5. stays in loop, but it's not an infinite loop (C++)
    By Berticus in forum C++ Programming
    Replies: 8
    Last Post: 07-19-2005, 11:17 AM