Path: csiph.com!weretis.net!feeder6.news.weretis.net!news.misty.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: "Alexei A. Frounze" Newsgroups: comp.compilers Subject: Re: Undefined Behavior Optimizations in C Date: Thu, 19 Jan 2023 21:18:52 -0800 (PST) Organization: Compilers Central Sender: johnl@iecc.com Approved: comp.compilers@iecc.com Message-ID: <23-01-065@comp.compilers> References: <23-01-027@comp.compilers> <23-01-031@comp.compilers> <23-01-041@comp.compilers> <23-01-062@comp.compilers> MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="1115"; mail-complaints-to="abuse@iecc.com" Keywords: C, optimize Posted-Date: 20 Jan 2023 11:16:59 EST X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com In-Reply-To: <23-01-062@comp.compilers> Xref: csiph.com comp.compilers:3333 On Wednesday, January 18, 2023 at 8:35:40 AM UTC-8, Spiros Bousbouras wrote: ... > I have encountered several times the claim that compilers assume that UB does > not happen and I don't understand it. Lets consider 2 examples : > > x + 1 > x > > in C where x is a signed integer. Compilers will often treat this as > always true with the following reasoning : > > - if x does not have the maximum value which fits in its type then the > meaning of the C expressions is the same as their mathematical meaning > so the expression evaluates to true. > > - if x has the maximum value which fits in its type then x + 1 is not > defined so any translation (including treating the whole expression as > true) is valid. > > There's no assumption that UB (undefined behaviour) will not happen, both > possibilities are accounted for. I believe in a case like this a modern C/C++ compiler reasons that x must be less than the maximum representable value and it generates code according to this, possibly removing dead code that depends on x being the maximum representable value. If the compiler's assumption that x is less than the maximum is wrong, it's perfectly fine, it's UB, any "broken" code generated is allowed. Alex