Adding message to assert

前端 未结 8 1623
花落未央
花落未央 2020-12-12 20:36

Hallo!

I\'m looking for a way to add custom messages to assert statements. I found this questions Add custom messages in assert? but the message is static there. I w

8条回答
  •  难免孤独
    2020-12-12 21:03

    For the sake of completeness, I published a drop-in 2 files assert macro implementation in C++:

    #include 
    
    int main()
    {
      float min = 0.0f;
      float max = 1.0f;
      float v = 2.0f;
      PEMPEK_ASSERT(v > min && v < max,
                    "invalid value: %f, must be between %f and %f", v, min, max);
    
      return 0;
    }
    

    Will prompt you with:

    Assertion 'v > min && v < max' failed (DEBUG)
      in file e.cpp, line 8
      function: int main()
      with message: invalid value: 2.000000, must be between 0.000000 and 1.000000
    
    Press (I)gnore / Ignore (F)orever / Ignore (A)ll / (D)ebug / A(b)ort:
    

    Where

    • (I)gnore: ignore the current assertion
    • Ignore (F)orever: remember the file and line where the assertion fired and ignore it for the remaining execution of the program
    • Ignore (A)ll: ignore all remaining assertions (all files and lines)
    • (D)ebug: break into the debugger if attached, otherwise abort() (on Windows, the system will prompt the user to attach a debugger)
    • A(b)ort: call abort() immediately

    You can find out more about it there:

    • blog post
    • GitHub project

    Hope that helps.

提交回复
热议问题