Author Topic: What’s wrong with this? simple C PROGRAMMING  (Read 275 times)

Offline modeezy23

  • Single posting newcomer
  • *
  • Posts: 3
What’s wrong with this? simple C PROGRAMMING
« on: March 28, 2019, 03:03:15 pm »
New to C programming.
How come this code is giving me a warning:

#include <stdio.h>
#include <stdlib.h>

int main()
{
        char answer;

        if(answer = ‘y’ || ‘Y’){       WARNING ON THIS LINE
                printf(“Yes”);
        }
        else if(answer = ‘n’ || ‘N’){     WARNING ON THIS LINE
                printf(“No”);
        }
        else if(answer != ‘y’ || ‘Y’ || ‘n’ || ‘N’){       WARNING ON THIS LINE
                printf(“Invalid Option\n”)
        }

        return 0;
}


Offline stahta01

  • Lives here!
  • ****
  • Posts: 6489
    • My Best Post
Re: What’s wrong with this? simple C PROGRAMMING
« Reply #1 on: March 28, 2019, 03:22:54 pm »
Find a website to ask your programming; this website does not teach programming.

http://forums.codeblocks.org/index.php/topic,9996.0.html

Tim S.
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org

Offline sodev

  • Almost regular
  • **
  • Posts: 242
Re: What’s wrong with this? simple C PROGRAMMING
« Reply #2 on: March 28, 2019, 09:03:35 pm »
Noobs teaching noobs programming... what comes next?

Bad post, use code tags.
Bad forum, use entry level programmer forum.

Offline sodev

  • Almost regular
  • **
  • Posts: 242
Re: What’s wrong with this? simple C PROGRAMMING
« Reply #3 on: March 29, 2019, 05:12:05 am »
Great, you fixed his code :). But sad, you didnt answer his question :(.

The answer is, each line except last (there only the second warning) should cause two warnings, one because of assignment in a conditional and one because of precedence of the || operator.

Because of the precedence the || operator gets evaluated first, the chars are interpreted in a boolean context, in every if the result is 1 and gets assigned to answer (except last if), so the result is always Yes ;D