Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let me paraphrase question to be more accurate in my answer:</p> <blockquote> <p>Can runtime assert <strong>sometimes</strong> report errors on compile time.</p> </blockquote> <p>Gcc can, but only on some optimization level and error message is very uninformative. Clang itself can't (no error attribute), but do not forget about clang <strong>analyzer</strong>. Analyzer can report some runtime errors like dereferencing null pointer.</p> <p>So here is an idea and simple test of 'smart' runtime assert:</p> <pre><code>#include &lt;cstdlib&gt; // std::abort #if !defined(__clang__) &amp;&amp; defined(__GNUC__) // clang emulates gcc # define GCC_COMPILER 1 #else # define GCC_COMPILER 0 #endif #if GCC_COMPILER void assertion_failed_message() __attribute__((__error__("assertion failed"))); #endif inline void smart_assert(bool condition) { #if GCC_COMPILER // gcc is very 'sensitive', it must be first code lines in this function if (__builtin_constant_p(condition) &amp;&amp; !condition) { assertion_failed_message(); } #endif if (condition) { // Ok return; } #if defined(__clang_analyzer__) enum { ASSERTION_FAILED = 0xdeadfull }; int *a = nullptr; *a = ASSERTION_FAILED; #endif // Implement some standart error, like abort std::abort(); } void test_condition_2(bool condition) { smart_assert(condition); } void test_condition_1(bool condition) { test_condition_2(condition); } void test_condition_0(bool condition) { test_condition_1(condition); } int main() { test_condition_0(0==1); return EXIT_SUCCESS; } </code></pre> <p>Gcc report error at O2 optimization level, it's good. But report message is in main function, and don't leave any information about test_condition_{0,1,2}.</p> <p>Clang analyzer report error and if you use Xcode, you can see all path from main to smart_assert: <img src="https://i.stack.imgur.com/ivjo6.png" alt="clang_analyzer_report"></p> <p><strong>P.S.</strong> clang analyzer is not perfect, so if you try test_condition_0(argc), no error will be reported (truely runtime check), but if you try test_condition_0(argc==1), false positive will be reported.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload