Protecting the world

from criminally bad code

strchr

synopsis

#include <string.h>

#ifndef __cplusplus

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

#else

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

#endif

Description

The strchr function searches for a given character within a null-terminated string. It returns a pointer to the instance nearest to the start of the string, or null if the search failed.

Pitfalls

Const incorrectness

In C, strchr 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.

Limitations

Search takes no account of multi-byte character encodings

When strchr 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.

Portability

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

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

Further reading

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