index and rindex question...

Bob Stout Bob.Stout at p6.f506.n106.z1.fidonet.org
Sat Feb 3 21:49:01 AEST 1990


In an article of <1 Feb 90 16:33:33 GMT>, (Karl Heuer) writes:

 >>#define index(s,c)  ((strchr((s),(c)))?(size_t)(strchr((s),(c))-(s)):-1)
 >>#define rindex(s,c) ((strrchr((s),(c)))?(size_t)(strrchr((s),(c))-(s)):-1)
 >>
 >>Note that these are *not* safe macros since the `s' argument may be
 >>evaluated three times and the `c' argument twice.
 >
 >They also do twice as much work, and would be confusing to anyone who 
 >expects those names to have the V7/BSD semantics.  Wouldn't it be simpler to 
 >just use strchr and strrchr, which should be present in any modern system?

  The point is that I use them primarily for porting code which *doesn't* use  
V7/BSD semantics and secondarily in situations where I need an array index  
rather than a pointer returned. Apparently you've never had a requirement for  
either. Although both circumstances are rare, both exist I can assure you.

  As for "doing twice as much work", any reasonably decent optimizing compiler  
will only call the function once although either macro could be implemented as  
a function in order to guarantee both safety and optimal execution speed. 



More information about the Comp.lang.c mailing list