18

I am doing something in C which requires use of the strings (as most programs do).

Looking in the manpages, I found, at string(3):

SYNOPSIS

#include <strings.h>

char * index(const char *s, int c)

(...)

#include <string.h>

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

So I curiously looked at both strchr(3) and index(3)...

And I found that both do the following:

The strchr()/index() function locates the first occurrence of c in the string pointed to by s. The terminating null character is considered to be part of the string; therefore if c is '\0', the functions locate the terminating '\0'.

So, the manpage is basically a copy & paste.

Besides, I suppose that, because of some obfuscated necessity, the second parameter has type int, but is, in fact, a char. I think I am not wrong, but can anyone explain to me why is it an int, not a char?

If they are both the same, which one is more compatible across versions, and if not, which's the difference?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
ssice
  • 3,564
  • 1
  • 26
  • 44

2 Answers2

27

strchr() is part of the C standard library. index() is a now deprecated POSIX function. The POSIX specification recommends implementing index() as a macro that expands to a call to strchr().

Since index() is deprecated in POSIX and not part of the C standard library, you should use strchr().

The second parameter is of type int because these functions predate function prototypes. See also https://stackoverflow.com/a/5919802/ for more information on this.

Gabriel Ravier
  • 358
  • 1
  • 6
  • 17
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • index() is also `part of the C standard library` anyway. But you are both right. – ssice Nov 03 '10 at 21:51
  • 3
    @ssice: No, it isn't. The word "index" doesn't appear anywhere in the C standard library specification (clause 7 of C99). – James McNellis Nov 03 '10 at 21:53
  • 2
    @ssice: who says `index()` is part of the C standard library? – Steve Jessop Nov 03 '10 at 21:55
  • 2
    @ssice: Your particular standard library implementation may have an `index()` function, but if it does it is a language extension. `index()` is not part of the C standard library. – James McNellis Nov 03 '10 at 22:05
  • 4
    @ssice: You get yourself a copy of the language standard (you can find out how from [this Stack Overflow question](http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents)). – James McNellis Nov 03 '10 at 22:11
2

It looks like the index() function is an older one that should be replaced by strchr(). See http://www.opengroup.org/onlinepubs/000095399/functions/index.html where they suggest to replace index by strchr and mark index as a legacy function.

Patrick
  • 23,217
  • 12
  • 67
  • 130