Protecting the world

from criminally bad code



#include <string.h>

#ifndef __cplusplus

char* strrchr(const char* s,int c);


char* strrchr(char* s,int c);
const char* strrchr(const char* s,int c);



The strrchr function searches backwards for a given character within a null-terminated string. It returns a pointer to the instance that is nearest to the end of the string, or null if the search failed.


Const incorrectness

In C, strrchr has the ability to convert a const pointer into a non-const pointer. There is a reason for this behaviour, but it is open to misuse and it can prevent the compiler from detecting some types of error.

See the page ‘Const-incorrect standard library functions’ for a more detailed discussion of this issue.


Search takes no account of multi-byte character encodings

When strrchr performs a search it operates on the assumption that each character occupies exactly one byte. For this reason it is not generally suitable for use with multi-byte character encodings.

A useful exception to this rule is that, in the particular case of UTF-8, it is possible to search for characters in the Basic Latin block (U+0000 to U+007F inclusive). These characters are represented by a single byte, and the bytes used for that purpose do not occur in other characters. UTF-8 therefore behaves like a single-byte encoding under these circumstances, even though it is not in the general case.


  •  C90
  •  C99
  •  C++98
  •  C++11

In C++, use of the header <string.h> is deprecated in favour of <cstring>.

Further reading

  • The strrchr function, Programming languages — C, ISO/IEC 9899:1999, §, p330
  • strrchr, The Open Group Base Specifications, Issue 7, The Open Group, 2008
  • strrchr(3), Linux Programmer’s Manual, The Linux man-pages project
  • Search Functions, The GNU C Library Reference Manual, The GNU Project