0

I have definition of macro printerr

#define CLR_R "\x1b[1;31m" 
#define CLR_N "\x1b[0m"
#define printerr(caller,msg) (caller==NULL)?printf(CLR_R "%s" CLR_N "\n",msg) \
   : printf(CLR_R "%s:" CLR_N " %s\n",caller,msg)

And get warning

warning: reading through null pointer (argument 2), when calling printerr(NULL,"error");.

How to suppress this warning?

#include <stdio.h>
#define printerr(caller,msg) (caller==NULL)?printf("%s\n",msg) : \
    printf("%s: %s\n",caller,msg)
void main() {
    printerr("Error","error occurred"); //will be ok
    printerr(NULL,"error"); //Warning: is caller even checked here?
}
15
  • 1
    what are CLR_R and CLR_N Commented Mar 29, 2017 at 17:17
  • Just char* constants #define CLR_R "\x1b[1;31m" #define CLR_N "\x1b[0m" Commented Mar 29, 2017 at 17:18
  • @SouravGhosh Why does it matter? I'm guessing they're escape sequences for switching to red and back to no color. Commented Mar 29, 2017 at 17:18
  • @Barmar ummm... maybe because it's better to have minimal reproducible example? Commented Mar 29, 2017 at 17:19
  • 1) Read How to Ask and provide a minimal reproducible example. 2) Don't use a macro where a function will do as well. Commented Mar 29, 2017 at 17:19

1 Answer 1

1

This works (gcc, clang):

#include <stdio.h>
int main()
{
#define CLR_R "\x1b[1;31m" 
#define CLR_N "\x1b[0m"

#define printerr(caller,msg)  \
    (caller==NULL)? printf(CLR_R "%s" CLR_N "\n",msg) : \
    printf(CLR_R "%s:" CLR_N " %s\n", ((caller)?(caller):""),msg)


    printerr(NULL,"msg");
    printerr("caller","msg");
}

I'm using ((caller)?(caller):"")to suppress the warning. It will never evaluate to "".

You could also use an inline function to the same effect:

#define CLR_R "\x1b[1;31m" 
#define CLR_N "\x1b[0m"
static inline int inl_printerr(char const *caller, char const *msg)
{
    if (caller)
        return printf(CLR_R "%s:" CLR_N " %s\n", caller,msg);
    else
        return printf(CLR_R "%s" CLR_N "\n",msg);
}

(Recommended as it avoids the typesafety and double-evaluation issues that macros have).

Sign up to request clarification or add additional context in comments.

2 Comments

I'm curious as to why it's been also marked "not useful", given that it is demonstrably useful to the OP. :(
Because the DV button is rather used for "I don't like it for a generic reason or having a bad mood".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.