Path: ...!npeer.as286.net!npeer-ng0.as286.net!3.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: What is your opinion about unsigned int u = -2 ?
Date: Sun, 11 Aug 2024 12:33:11 -0700
Organization: A noiseless patient Spider
Lines: 27
Message-ID: <86y152n9c8.fsf@linuxsc.com>
References: <87mslxe4wj.fsf@bsb.me.uk>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Date: Sun, 11 Aug 2024 21:33:12 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="e27eccf1f18fd326d4b617bedae077c0";
logging-data="2984033"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/bxtLhjUwACwzx/frq9ayu470lao4fvRA="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:d0l2mYO9MloIOVhRVUiG07xnJhA=
sha1:Ss4+cIU4gla8jUE8fwDC54ozKFY=
Bytes: 1868
Ben Bacarisse writes:
> Thiago Adams writes:
>
>> What is your opinion about this:
>>
>> unsigned int u1 = -1;
>>
>> Generally -1 is used to get the maximum value.
>
> Yes, that's a common usage, though I prefer either -1u or ~0u.
>
>> Is this guaranteed to work?
>>
>> How about this one?
>>
>> unsigned int u2 = -2;
>> Does it makes sense? Maybe a warning here?
>
> Warnings are almost always good, especially if they can be configured.
> For example you can ask gcc to warn about converting -1 to unsigned
> while leaving -1u and ~0u alone.
Ick. That choice is exactly backwards IMO. Converting -1 to
an unsigned type always sets all the bits. Converting -1u to
an unsigned type can easily do the wrong thing, depending
on the target type.