Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.unix.programmer,comp.lang.c Subject: Re: Odd compiler behaviour? Date: Tue, 01 Mar 2016 08:36:27 -0800 Organization: None to speak of Lines: 48 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="27485"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/6BGhz9bA7Z1t6LQYeQjhO" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:YI1zH/8JzO9kEoUZJ6pButtrlfA= sha1:LklwpWFAZ8G6/qcc3gsqFdR0uzM= Xref: csiph.com comp.unix.programmer:7963 comp.lang.c:82867 spud@potato.field writes: > On Tue, 01 Mar 2016 15:46:42 +0100 > David Brown wrote: >>On 01/03/16 14:48, spud@potato.field wrote: >>> On Tue, 01 Mar 2016 12:57:54 +0100 >>> David Brown wrote: >>>> On 01/03/16 12:06, spud@potato.field wrote: >>>> It is slightly disappointing that neither gcc nor clang will warn about >>>> the case of "int s = 32; 1 << s;" - there is no reason why they could >>>> not do so. >>> >>> Presumably because 'i' won't be initialised until runtime and the compiler >>> would have to check all execution paths to see if the value it contained >>> by the time it got to the shift was valid. And things would get even more >>> complicated if an expression was used instead. Probably not worth the effort. >>> >> >>The compiler can happily see that "s" is initialised to 32, and that >>this value will not change. gcc uses this to determine that the value >>is undefined, and sets the relevant register for the printf call to 0 > > The 1 << s actually returns 1 , not zero. The hard coded value returns zero. > Also this code gives the same result if you enter 32. So unless gcc is psychic > the '1' result is calculated at runtime, not compile time: It depends on the optimization level. Experiment shows that gcc generates code to compute `1 << s` at run time if optimization is not enabled, but computes it at compile time with -O1 or higher. You can use the "-S" option to examine the generated assembly code. > int main() > { > char str[10]; > int s; > gets(str); > s = atoi(str); > printf("%d\n",(int)1 << s); > return 0; > } Why are you calling gets()? -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"