Jump to: navigation, search

Description

The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte.

Return value

The strlen() function shall return the length of s; the function has no failure mode and no error return.

Prototype

Declared in string.h

size_t strlen(const char *s);

Implementation

Portable approaches

#include <stddef.h> /* for size_t */
size_t strlen(const char *s) {
    size_t i;
    for (i = 0; s[i] != '\0'; i++) ;
    return i;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none JesseW (partial);

The following is slightly less portable code although it meets all of the requirements of the Standard - see the talk page for details.

#include <stddef.h> /* for size_t */
size_t strlen(const char *s) {
    const char *p = s;
    while (*s) ++s;
    return s - p;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none

References

Personal tools