开发者

Receiving function name in C

开发者 https://www.devze.com 2023-04-07 19:50 出处:网络
I have a program like this, void test(char* a) { printf(\"%s\",a); // Trying to print the function name \"add\" here

I have a program like this,

void test(char* a)
{   
    printf("%s",a); // Trying to print the function name "add" here
    return;
}

int add(int,int)
{
  test(__FUNCTION__); // I need the function name add to be passed to the test functio开发者_开发问答n
  ...................
  ....................
}

But while building I am getting the error in a C compiler(gcc flavour) like this,

passing argument 1 of 'test' discards qualifiers from pointer target type

Please have a look at this,

/R


From here:

The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.

__FUNCTION__ is another name for __func__.

So, you're trying to pass a const char * to a char *, discarding the const qualifier. Since in your test function you aren't modifying the passed string, change its parameter type to const char *, promising to the caller that you aren't modifying its string.

By the way, to get const correctness right you should always remember to declare pointers as const if they are "input-only" parameters.


Change the signature of test to

void test(const char* a)

GCC is complaining that you're converting a pointer to a constant string literal to a mutable pointer by calling test.

0

精彩评论

暂无评论...
验证码 换一张
取 消