Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve this MISRA warning: C++

Tags:

c++

misra

Here is the code as below:

  std::stringstream os;

  os << std::hex; // MISRA warning on this line
  os << std::setw(2);
  os << std::setfill('0');

Warning: "Required Rule 8-4-4, function identifier used without '&' or parenthisized parameter list"

I am not able to resolve this, please suggest a solution.

like image 527
suhel Avatar asked Dec 04 '22 07:12

suhel


2 Answers

Do what the warning says: take the address of the function:

os << &std::hex;
like image 73
Angew is no longer proud of SO Avatar answered Dec 09 '22 14:12

Angew is no longer proud of SO


How about just using & like suggested ?

#include <iomanip>
#include <iostream>
#include <sstream>

int main() {
    std::stringstream os;

    os << &std::hex; // Works with &
    os << std::setw(2);
    os << std::setfill('0');
    os << 13;

    std::cout << os.str() << "\n";
    return 0;
}

Yes, it works too.


What is the difference ?

  • std::hex is a reference to function
  • &std::hex is a pointer to function

Since references to function have an implicit conversion to pointers to function, you can pass either to an ostream and it will work as expected. Apparently, though, MISRA requires you to be explicit on whether you meant I want the function or I want to invoke the function.

like image 39
Matthieu M. Avatar answered Dec 09 '22 15:12

Matthieu M.