beltoforion / muparserx

A C++ Library for Parsing Expressions with Strings, Complex Numbers, Vectors, Matrices and more.
http://beltoforion.de/en/muparserx
BSD 2-Clause "Simplified" License
136 stars 60 forks source link

int to bool conversion #117

Closed psynetic closed 1 year ago

psynetic commented 1 year ago

I get an conversion exception when using functions which are returning int in conjunction with 'and' or 'or'.

From C++11: When any scalar value is converted to bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

I could solve the problem by disabling CheckType for Value::GetBool().

bool Value::GetBool() const { //CheckType('b'); return m_val.real() == 1; }

or

bool Value::GetBool() const { if (m_cType != 'b') { return ((bool)m_val.real()) == 1; }

CheckType('b');
return m_val.real() == 1;

}

beltoforion commented 1 year ago

I'm not striving to match C++ behavior. The test fails because the types are different. The implicit cast from int to bool and vice versa is inherently dangerous and allows for some syntax I do not want to support. Like abusing it for if-then else assignments:

(a<b) * 123 + (a>=b) *456

Your solution will work but for the time being i do not want to allow it.

psynetic commented 1 year ago

Thanks for clarification.

But in type-strict environment func f1 which returns type mup::bool_type and the value false should throw also something like 'incomparable types: boolean and int'

with the expression:

f1()==0

In that case the return value (0) for m_Value (Value) is wrong.

beltoforion commented 1 year ago

The test will return false if the types differ. This may not be expected and is indeed inconsistent. I will fix it.