Search code examples
c++gccvolatile

Why is volatile not compiling with std::min


Why is following code not compilable (gcc-5.4.0)?

volatile int i{100};
int j{200};
std::cout << std::min(i, j);

I mean I see the compiler error:

error: no matching function for call to ‘min(volatile int&, int&)’

Isn't volatile just hint to compiler, that the variable could change from outside of the program?

std::min(int(i), j);

Is of course working. But shouldn't original work too?


Solution

  • volatile is a qualifier just like const. It's more than a mere hint to the compiler.

    std::min expects the two parameters to have exactly the same types and qualifiers. So in your case it issues a diagnostic.

    Since you are allowed to introduce qualifiers, you could indulge in a little hand-holding and write

    std::min<volatile int>(i, j)