Differences Between C and C++ in the Prototypes of Standard Functions

A small number of functions from the Standard Library have different signatures on C and C++. These functions are: strchr(), strpbrk(), strrchr(), strstr(), and memchr() as well as their wide-character counterparts: wcschr(), wcspbrk(), wcsrchr(), wcsstr(), wmemchr(). They are declared in the standard header Let’s look at strstr() for example.

While in C strstr() has the following prototype:

  char *  strstr(const char*s1, const char *s2);

In C++, this function has two different prototypes that are incompatible with the C version:

  char * strstr(char *s1, const char * s2);  const char * strstr(const char * s1, const char *s2); 

Let’s look at another example: the function strpbrk(). In C, it has the following signature:

  char * strpbrk(const char *s1, const char *s2); /*ANSI C*/

In C++, it has two different signatures:

  char *  strpbrk(char *s1, const char *s2);   const char * strpbrk(const char *s1, const char *s2);

Can you see a pattern here? The C version takes “const X *””as an argument and returns “X *”, whereas C++ defines two versions: one taking “X *” as an argument and returning “X *”, and another taking “const X *” as an argument and returning “X *”. In C++ you have better type-safety, which is feasible thanks to function overloading.

You should pay attention to these subtle differences between C and C++ when you port code from C to C++.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: