Path: csiph.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: signed vs unsigned and gcc -Wsign-conversion Date: Mon, 15 Dec 2025 00:25:01 -0800 Organization: A noiseless patient Spider Lines: 32 Message-ID: <86bjk0up7m.fsf@linuxsc.com> References: <10d5j0v$3kdmk$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Date: Mon, 15 Dec 2025 08:25:04 +0000 (UTC) Injection-Info: dont-email.me; posting-host="3b66f75cc16331490dd39d06d7ef9603"; logging-data="1839657"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/pwabsJvyWI0X569dA7fT5J0S8C9hbraE=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:rbArMG6pkOIogckxbyjXs+BTzo4= sha1:ecfRGDaq83lUX9+dysOBlRK0a0g= Xref: csiph.com comp.lang.c:395812 pozz writes: > After many years programming in C language, I'm always unsure if it is > safer to use signed int or unsigned int. > > Of course there are situations where signed or unsigned is clearly > better. For example, if the values could assume negative values, > signed int is the only solution. If you are manipulating single bits > (&, |, ^, <<, >>), unsigned ints are your friends. > > What about other situations? For example, what do you use for the "i" > loop variable? I used unsigned types unless there is a compelling reason to use signed types. I used unsigned types for counts, array index values, sizes, lengths, extents, limits of the above, bits and masks. The most common reason for using signed types is for compatibility with some system interface (most commonly, signed int). There are cases where using an unsigned type rather than a signed type requires more thought and care. To me that need is a net positive rather than a negative. > I recently activated gcc -Wsign-conversion option on a codebase and > received a lot of warnings. I started to fix them, usually expliciting > casting. Is it the way or is it better to avoid the warning from the > beginning, choosing the right signed or unsigned type? My experience with such warnings is they generate too many false positives. I might turn on -Wsign-conversion every now and then as a sanity check, but not all the time. The "cure" of changing the code so the warnings go away is worse than the disease.