DSR
DSR

Reputation: 3

Warning in Function pointer as a argument to another function

Just tried function pointer as an argument. Following code executed properly but throwing some warning. Not able to understand the warring. Can have some help here.

#include<stdio.h>
#include<string.h>

int concat(char *str1, char *str2, char *(*cat_fun) (const char *, const char *))
{
   char str;

   if(cat_fun) {
       printf("%s\n",cat_fun (str1,str2));
       return 0;
   } else {
        return 1;
   }
}

int main(void)
{
    char str1[20] = "super ";
    char str2[] = "computer";

    concat(str1,str2,strcat);
    return 0;
}

Compilation:

 gcc tttt.c    
tttt.c: In function ‘main’:    
tttt.c:22:2: warning: passing argument 3 of ‘concat’ from incompatible pointer type [enabled by default]    
  concat(str1,str2,strcat);    
  ^
tttt.c:4:5: note: expected ‘char * (*)(const char *, const char *)’ but argument is of type ‘char * (*)(char * __restrict__,  const char * __restrict__)’    
 int concat(char *str1, char *str2, char *(*cat_fun) (const char *, const char *))
     ^

Upvotes: 0

Views: 54

Answers (2)

This is the declaration of strcat:

char *strcat(char *dest, const char *src);

The first parameter is not a const pointer, because the function is supposed to modify that buffer. But your function pointer accepts that first parameter as a pointer to a const buffer, which is a promise that the pointee will not be modified. Naturally, that's a semantic incompatibility.

Strictly speaking, the C type system doesn't allow implicitly converting strcat to the pointer type you specify. But compilers may accept it in the interest of backward compatibility to older C versions, and emit only a warning. Bumping the standard compliance level in your build can help turn it into an error (and as such, maybe prevent nasty bugs down the line).

Upvotes: 1

user8027470
user8027470

Reputation:

The first argument is char*, not const char*.

See here:

https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm

Upvotes: 0

Related Questions