Path: csiph.com!3.us.feeder.erje.net!feeder.erje.net!news.linkpendium.com!news.linkpendium.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: David Brown Newsgroups: comp.compilers Subject: Re: Bounds checking, Optimization techniques and undefined behavior Date: Wed, 8 May 2019 10:03:08 +0200 Organization: A noiseless patient Spider Lines: 53 Sender: news@iecc.com Approved: comp.compilers@iecc.com Message-ID: <19-05-061@comp.compilers> References: <19-04-021@comp.compilers> <19-04-023@comp.compilers> <19-04-037@comp.compilers> <19-04-039@comp.compilers> <19-04-042@comp.compilers> <19-04-044@comp.compilers> <19-04-047@comp.compilers> <19-05-004@comp.compilers> <19-05-006@comp.compilers> <19-05-016@comp.compilers> <19-05-020@comp.compilers> <19-05-024@comp.compilers> <19-05-025@comp.compilers> <19-05-028@comp.compilers> <19-05-029@comp.compilers> <19-05-034@comp.compilers> <19-05-045@comp.compilers> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="52666"; mail-complaints-to="abuse@iecc.com" Keywords: C, optimize, comment Posted-Date: 08 May 2019 12:33:40 EDT X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com Content-Language: en-GB Xref: csiph.com comp.compilers:2296 On 07/05/2019 11:04, David Brown wrote: > [For the loop with the unchangable index, you can declare the index > const and cast the places you change it, but ugh. > > const int i; > > for(*(int*)&i = 0; i < 10; (*(int*)&i)++) { > a[i] = i; > i++; /* will be diagnosed as an error */ > } > -John] > Looking more closely at your code here, it is wrong. You can cast away "const" from something that was originally declared without "const" and had "const" added via a cast. You cannot cast away "const" from something declared "const". The compiler is free to assume that "i" never changes, and ignore (or complain about) your attempts to change it via the casts. There is a much better way, but it is still ugly: for (int i = 0; i < 10; i++) { const int ii = i; const int i = ii; a[i] = 1; i++; // Error } You can, of course, just use a new local const variable, but then you lose the matching names. In C++, this won't work because the first "int i" scope is /inside/ the compound statement, while in C it is /before/ that statement. In C++, you need: for (int i = 0; i < 10; i++) {{ const int ii = i; const int i = ii; a[i] = 1; i++; // Error }} So it can be done, but it would be nicer if it were better integrated in the language. For a new language, I would make such immutability part of the definition of the "for" loop. [I'm looking at C11 and don't see where it says you can't cast away const. What am I missing? I agree any approach here is ugly and we're near the limits of what you can say in C. -John]