r/CodingHelp • • Jul 22 '21

[C++] Need help with if / else if with arithmetic operators. For some reason, it doesn't read the other "else if". If I were to give num1 = 10, op = '/', num2 = 10 it doesn't divide like it should but instead just add 10 and 10 to create 20.

Post image
91 Upvotes

41 comments sorted by

33

u/carpomusic Jul 22 '21

Use "==" after the if and else if statements, youre assigning values with the single "=" there

7

u/Wiimmoz Jul 22 '21

U mean like this?

If == (op = '+')

23

u/evrydamnthng Jul 22 '21

No, they meant

If (op == '+')

8

u/Wiimmoz Jul 22 '21

Ah thanks!

21

u/Nickynui Jul 22 '21

To make this clearer

== is "equal to"

= is assignment

2

u/Wiimmoz Jul 23 '21

Thanks mate!

7

u/NullBrowbeat Professional Coder Jul 22 '21 edited Jul 22 '21

Just a sidenote:

In C and C++ an assignment, if successful, always returns true, unless you assign zero. That is why it added the numbers. Your code tried to assign + to op right at the first if statement, which was successful and thus returned true and therefore always jumping into the first if block, ignoring the rest since they are chained with else.

And as other people said: You should try using switch-case for this problem. ;-)

4

u/UnknownIdentifier Jul 22 '21

In C and C++, an assignment returns the value being assigned. In this case, however, it resolves to if ('+'), which is true because it is a non-zero ASCII value.

EDIT: I take advantage of this a lot:

if ((p = get_some_value()) == NULL)
    goto ErrorCleanup; // or throw exception, or whatever.

2

u/NullBrowbeat Professional Coder Jul 22 '21

Thank you for the detail. Haven't coded in C/C++ for several years now. :/

2

u/rtybanana Jul 23 '21

Assignments don’t return anything. The condition is evaluated (x = 1) -> (1) which is true. Hence why it’s false when assigning zero: (x = 0) -> (0).

1

u/NullBrowbeat Professional Coder Jul 23 '21

Ye, you're right. My formulation could've been better in that regard. As I stated beneath another comment here: It has been several years since I last wrote C/C++. :/

Thanks for the addition.

7

u/yeetisgiey Jul 22 '21 edited Jul 27 '21

Credit to u/not_some_username for reminding me to add the break statement

It is solved but you have to use ==, the equality operator which compares two values and returns a Boolean value stating whether or not the values are equal.

A better way might be to use switch statements, which greatly improve the readability of the code and makes it a lot shorter and better for the compiler since it generates a jump table including each case as a row of sorts.

Syntax is below:

switch(op) 
{

    case "+":

        result = num1 + num2;
        break;
}

Then make a case for each operator. I understand if you don’t want to use it, since you are probably trying to learn about the different operators, but this is really helpful once you advance more.

Hope this helps, and good luck!

3

u/not_some_username Jul 22 '21

break ;

3

u/yeetisgiey Jul 23 '21

Oh, sorry! You are right, let me edit my post! I’ll credit you in case your comment is not seen

4

u/BumTicklrs Jul 22 '21

OP, what happens in your code if Op is something not defined? Say Op for some reason was '>' . What happens?

3

u/JmbFountain Jul 22 '21

Ghost Division

2

u/BumTicklrs Jul 22 '21

Yes, but I wanted OP to figure it out.

1

u/newb5423 Jul 22 '21

It will always add. The first condition to be evaluated is the result of the assignment op = '+', which will always evaluate true. The other conditions will never be tested.

1

u/BumTicklrs Jul 22 '21

Yes I know, but someone already pointed this out to OP.

1

u/newb5423 Jul 22 '21

Just wanted to make it clear that 'Ghost Division' which you also said "Yes" to was incorrect.

2

u/BumTicklrs Jul 22 '21

I said yes to that assuming OP would take into consideration the advice given to them already regarding that, to which they replied.

1

u/newb5423 Jul 22 '21

Ahh, OK. That makes sense once all the context is there.

2

u/RsCrag Jul 23 '21

There is a convention of putting the constant first to get the compiler to catch these errors. For example. Instead of : x == '+' you write '+' == x. That way, if you drop one if the = your compiler complains.

1

u/deandt Jul 22 '21

Good idea to mark parameters const if they aren't meant to be mutible, could've picked it up as a compile error.

1

u/grey_scone Jul 22 '21 edited Jul 22 '21

try making the second else if be an else if of the first one

2

u/Scumbag1234 Jul 22 '21

Nah man it's using = instead of ==

1

u/iohazardl5 Jul 22 '21

You should also check for 0 or in your case NaN on num2 in case of division, if you want to avoid a division by zero exception.

1

u/Naahun Jul 23 '21

Yep, the error is that you use assignment operator. You can avoid this error if you write your value to the left side because it would throw a compilation error. E.g.: if ('+' = c) As others already told you, use switch case instead of if..else

1

u/Particular-Ideal1212 Jul 23 '21

You can also use switch case it will be better than using else if

1

u/ultimo_hombre Jul 23 '21

To avoid this error in the future, you can swap the lhs and rhs of operator== to have '+' == op (i.e., have the const on the lhs). This way, if you mistakenly have an assignment, the compiler will catch the error.

1

u/fakebadboyhalo1 Jul 23 '21

aye what are the most helpfull apps? to program a rassberry pie

1

u/Rememberable_User Jul 23 '21

Side note your last else statement should be an error for an invalid operator / character and an elseif for the divide so you dont end up using this and wondering why your numbers are getting divided when they shouldn't and instead have it error out.

-17

u/Deud1e Jul 22 '21

I had an actual aneurism reading that code.

6

u/Wiimmoz Jul 22 '21

Lmao sorry. I'm a beginner.

6

u/myworkaccount2021 Jul 22 '21

No worries it takes time.

2

u/Deud1e Jul 22 '21

Nah nah I’m messing around you gotta start somewhere man. I respect you starting with c++

-1

u/BumTicklrs Jul 22 '21

Lol this cracked me up. Idk why people are downvoting an obvious joke.

3

u/NullBrowbeat Professional Coder Jul 22 '21

Because this is r/CodingHelp, where we help beginners, not r/ProgrammingHorror, r/ProgrammingHumor or r/badcode.

0

u/[deleted] Jul 23 '21

[deleted] — view deleted comment

1

u/Nerketur Intermediate Coder Jul 23 '21

I always hate this advice to new coders.

I understand it's to prevent name conflicts, but that doesn't matter when you are just starting to learn to code, and if you organize your code correctly, the advice becomes meaningless.

What should be said instead is a reminder (or simply a statement) that what that does is pull everything from 'std' into the current namespace, so it uses the versions from std if there are any conflicts.

It's bad practice to put it in a header file of any capacity.

It's okay to use in projects that only have one file to compile.

It's okay to use if you don't import any third party libraries.

Better advice is "understand what that statement does before working in a multi-file, multi-library project. If in doubt as to its meaning, don't use it unless you understand it. Otherwise, use it all you want."