-2

I would like to be able to do something like this:

   void f(int*p = nullptr)
    {
    if (!p)
{
//HERE I WOULD LIKE TO HAVE AN MSG THAT WOULD BE DISPLAYED DURING COMPILATION AS A WARNING POSSIBLY
}
    }
There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194
  • 12
    You want a warning at compile time, depening on what's happening at runtime? In general that's not possible. Perhaps you want something slightly different that we can actually help with? Please elaborate on the problem you are trying to solve :) – Magnus Hoff Nov 15 '10 at 19:22
  • 5
    Why would the function provide an illegal default argument `nullptr`? That's rather pointless, isn't it? :) – fredoverflow Nov 15 '10 at 19:24
  • @FredOverflow - it isn't pointles if you look at this from the point of view that depending on policy this function is run with pointer passed or with nullptr ;) – There is nothing we can do Nov 15 '10 at 19:46
  • 1
    @There: You still haven't answered the fundamental question: How can you generate a *compiler* error for something that happens at *runtime*? – John Dibling Nov 15 '10 at 19:51
  • 1
    And if it didn't have a default parameter, you would get a compiler error if you tried to call it without arguments. – UncleBens Nov 15 '10 at 19:55

4 Answers4

20

To generate a compile time warning based on a runtime check, simply create a file called "warning.c" that contains an unused variable declaration. You can then generate warnings like that:

void f(int *p = nullptr) {
    if (!p) {
        system("gcc -Wall warning.c");
    }
}
Amnon
  • 7,652
  • 2
  • 26
  • 34
10

The correct answer is: What you're trying to do won't ever work.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
5

Most, if not all, compilers support the #error and #warning preprocessor directives.

Microsoft's compiler, though, uses #pragma message() instead of #warning.

Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
3

Google #if #endif and #error preprocessor directives. It won't be possible to generate compile error based on the value of a variable that is not available at compile time, so forget about it. Use assert().

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434