Distinguishing const char * and char * with C _Generic macro

789 views c
6

I want a function to behave differently when parameter is a const char * (like "text") or char * (dynamically allocated string).

Is there a way to achieve this using _Generic macro in C?

I tried following code but it didn't run const function.

#define foo(val) _Generic((val), \
    char *: foo_string,\ 
    const char*: foo_const_string\
    )((val))

answered question

best to post calling code that "didn't run const function" as it "works" for me. Note "text" is an "array 5 of char", not a const. Try const char *s = "text"; foo(s);

I see, is there a way to handle general "array N of char" for any N? @chux

Try (val) --> ((val) + 0) to compel conversion to pointer type. Maybee even (val) --> (+(val)). Still hoping for a Minimal, Complete, and Verifiable example.

1 Answer

10

This code runs fine, so the problem should be the code which calls the macro.

tested with gcc.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0

#include <stdio.h>

void put_const_msg( const char* msg )
{
  printf("CONST MSG: %s\n", msg);
}

void put_non_const_msg( char* msg )
{
  printf("NON CONST MSG: %s\n", msg);
}

#define put_msg(msg) _Generic((msg), \
    const char*: put_const_msg, \
    char*:  put_non_const_msg \
                              )((msg))

int main ( int argc, char** argv )
{
  const char* cm = "Hello there!";
  char* ncm = "How are you?";

  put_msg(cm);
  put_msg(ncm);

  return 0;
}

Output

CONST MSG: Hello there!
NON CONST MSG: How are you?

posted this

Have an answer?

JD

Please login first before posting an answer.