-6

Why won't this work, I'm very new to programming but I can't seem to figure out why this wont work correctly.

#include <stdio.h>
#include <math.h>

int main(){
    int num1;
    printf("Enter 1, 2, 3.");
    scanf("%d", &num1);
    if(num1 = 1)
        printf("You entered one");
    else if(num1 = 2)
        printf("You entered two");
    else if(num1 = 3)
        printf("You entered three");
    else
        printf("Invalid");
}
simonc
  • 41,632
  • 12
  • 85
  • 103

6 Answers6

9

In C it is valid to use assignment (int x = 5) within a conditional (if statement).

For example:

int x = 0;

if (x = 5)
{

}

This will evaluate to true (it returns 5 to the "if" and all non zero terms are true by convention) if the assignment could be done and the value != 0. Which, in this case, it can be done and returns 5.

You were likely looking for this:

int x = 0;

if (x == 5)
{

}

This will evaluate to false (0).

Remember: You use a single equal sign "=" to mean "assignment". Use a double equal sign "==" to mean "comparison".

Community
  • 1
  • 1
MrHappyAsthma
  • 6,332
  • 9
  • 48
  • 78
6

Replace all the = with == and you should be fine (because = is used for assignment, while == is used to test for equality, which seems to be what you want to do)

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Tomer Arazy
  • 1,833
  • 10
  • 15
2

In C, as in other many programming languages, the = operator means "assignment". When you do a = 3, that means "assign a with 3", which of course it's something that succeeds and returns true, that's why your program will always enter the first branch.

What you have to do is use the "equality testing" operator, ==, so that a == 3 returns true if and only if the value held by variable a is 3.

fanton
  • 720
  • 5
  • 19
0

Your code having one mistake you have taken = instead of ==, in C = operator means assignment operator while== operator is used for comparision.

To clear about your doubts regarding operators read this link http://www.tutorialspoint.com/cprogramming/c_operators.htm

EAGLE
  • 586
  • 1
  • 6
  • 15
0

And because you started with int main() just for compiler reasons put return 0; at the end of your program to be more correct.

Spyros Chiotakis
  • 239
  • 1
  • 10
  • 2
    From C99 the `return 0;` is implicit, and if we want to be correct, the signature should be `int main(void)`. – effeffe Jun 03 '13 at 09:28
0

It doesn't work because you need to change the = sign to ==. You use the equal sign sometimes when you declare a int or char. == is meaning equal to and you want to use that when your not declaring ints and chars.While != means not equal.You should also put a return 0; at the end of your program.

falsetru
  • 357,413
  • 63
  • 732
  • 636
LFM
  • 113
  • 6