Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't "0" == "0"?

I do not have UNICODE in this project. This is a WinAPI project and the variable "input" is a stringstream with the default value "0". Why does the first id statement run and not 2nd one even though the string itself IS "0"?

void calc::AddToInput(int number)
{
    MessageBox(NULL, input.str().c_str(), "Input", NULL); //Shows "0"

    if(input.str().c_str() != "0") //Runs even though it shouldn't
    {
        input << number;
    }
    else if(input.str().c_str() == "0") //Doesn't run though it should
    {
        input.str("");
        input << number;
    }
}
like image 558
Tobias Sundell Avatar asked Jan 27 '14 20:01

Tobias Sundell


People also ask

Why does 0 not exist?

Does the number 0 actually exist? Without getting too philosophical about the meaning of `exist': yes. Mathematically it exists (was introduced) as a neutral element for addition; the defining property of 0 is that 0+a=a for all numbers a.

How do you prove 0 0 is not defined?

In ordinary arithmetic, the expression has no meaning, as there is no number which, multiplied by 0, gives a (assuming a≠0), and so division by zero is undefined. Since any number multiplied by zero is zero, the expression 0/0 also has no defined value; when it is the form of a limit, it is an indeterminate form.

Is 0 divided by 0 allowed?

So zero divided by zero is undefined. So, let's label it as that. Make sure that when you are faced with something of this nature, where you are dividing by zero make sure you don't put an actual number down, or a variable down.

Why is it impossible to divide by zero?

The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.


2 Answers

Comparing C-style strings with == means "Do the first elements of these strings have the same address?". It doesn't actually compare the contents of the strings. For that, you need strcmp.

However, you have no reason to compare C-style strings - just use the std::string returned from str(), which can be compared using ==, like so: input.str() != "0".

like image 200
Joseph Mansfield Avatar answered Oct 24 '22 03:10

Joseph Mansfield


Because you're comparing pointers, not strings. To compare strings either A) just compare the std::string instead of using c_str() (best), or B) use strcmp.

like image 40
Ed S. Avatar answered Oct 24 '22 04:10

Ed S.