使用C _Generic宏来区分const char *和char *

时间:2018-11-04 00:25:37

标签: c generics c-strings

当参数为const char *(如“文本”)或char *(动态分配的字符串)时,我希望函数的行为有所不同。

有没有一种方法可以在C语言中使用_Generic宏来实现?

我尝试了以下代码,但未运行const函数。

编辑:添加了示例

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

char * text = "abc";
foo(text);  //both calls foo_string(val)
foo("abc");

1 个答案:

答案 0 :(得分:0)

仅当您传递真正的const字符串指针时,“ const”版本才会运行,因此您要么将其存储在const指针变量中,要么手动将文字转换为“ const char *”。谢谢@David Bowling。

  

使用gcc.exe(i686-posix-dwarf-rev0,由MinGW-W64项目构建)测试8.1.0

包括

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);
  put_msg("KETCHUP IS A GENERIC SAUCE!");
  put_msg((char*)"MUSTARD IS LESS GENERIC!");
  put_msg((const char*)"Well this is ackward!");

  return 0;
}

输出

CONST MSG: Hello there!
NON CONST MSG: How are you?
NON CONST MSG: KETCHUP IS A GENERIC SAUCE!
NON CONST MSG: MUSTARD IS LESS GENERIC!
CONST MSG: Well this is ackward!