Shady Atef
Shady Atef

Reputation: 2401

Implicit casting acting strange

I have a question about implicit casting for the following code

#include <iostream>
using namespace std;


float max(int a, int b)
{
    if (a > b)
        return a;
    else return b;

}

int main() {
    double a, b;
    cin >> a >> b;
    cout << max(a, b)<<endl;
    cout << a;


    return 0;
}

Now Supposing that a = 30.5 & b = 26.4.

The anticipated result is 30 however on one computer(MinGW & VS 2005) I get 30.5.

Does anyone have an interpretation for this ? It makes no sense to me.

Edit 1 : Implicit conversion acting strangely

on third line output is 30.5 instead of the anticipated 30

Solution
std::max() is shadowing it, but why it shadows it on one computer and it doesn't on another I didn't investigate in that.
So try to avoid naming your functions or classes with names reserved for the standard library.

Upvotes: 0

Views: 66

Answers (1)

yizzlez
yizzlez

Reputation: 8805

This is whats resulting in the weird output:

using namespace std;

When calling max() you may be calling std::max() which may be included in <iostream> with no guarantees. Try this:

cout << ::max(a, b)<<endl; //forces global scope

Should print out 30.

Upvotes: 4

Related Questions