Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: An experimental max_n for int's...
Date: Sat, 29 Aug 2020 05:33:07 -0700
Organization: A noiseless patient Spider
Lines: 50
Message-ID: <86wo1h8we4.fsf@linuxsc.com>
References:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="fa701d7c3dfeeb40f6257600f67e6301"; logging-data="16695"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18PyZnrULU/2d9YpeajSKuIJBaJD3w6zgw="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:wXRLuEfEm3m4F1HHKx4duLLwjKM= sha1:g9A/WsXU5xzf33mQsLBzrKNG8yU=
Xref: csiph.com comp.lang.c:154169
"Chris M. Thomasson" writes:
> What do you think of this wrt max_n specialized for ints:
> ____________________________
> #include
> #include
> #include
>
>
> int max2(int a, int b)
> {
> if (a > b) return a;
> return b;
> }
>
>
> int max_n_int(int* p, size_t sz)
> {
> assert(sz > 0);
>
> int result = p[0];
>
> for (size_t i = 1; i < sz; ++i)
> {
> result = max2(result, p[i]);
> }
>
> return result;
> }
> [...]
>
> Is there a better way to write this?
I would be inclined to write something more like this:
#include
#include
static int
maximum( int *v, size_t n, int r ){
return n == 0 ? r : maximum( v+1, n-1, r < *v ? *v : r );
}
int
max_n_int( int *p, size_t n ){
return maximum( p, n, INT_MIN );
}
The INT_MIN is there to handle the degenerate case of arrays
with no elements.