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:51:46 -0800 Organization: None to speak of Lines: 46 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="U2FsdGVkX18H3JpI+e9PRHqEQyKPMLwk" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:5eVVv9PRuxcXRtZSyZ+/y3xvBu8= sha1:4SWFrCqz3rC5Lei+p0fYAt/JaRI= Xref: csiph.com comp.unix.programmer:7966 comp.lang.c:82870 spud@potato.field writes: > On Tue, 01 Mar 2016 08:36:27 -0800 > Keith Thompson wrote: >>spud@potato.field writes: >>> 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. > > How can it compute it at compile time if it doesn't know what the > value of 's' is going to be? It can't, of course. In the example I was referring to, the value of s *can* be determined at compile time, and gcc does so with "-O1" or higher. >>> 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()? > > Why in this example or why at all because its an unsafe function? > > Its an easy way to get user input in a simple example to demonstrate that the > output from printf can't possibly be computed at compile time since the user > enters the shift value at runtime. Ok. Using gets() obscured the point you were making. It's not merely unsafe; it's been removed from the language as of the 2011 standard. -- 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"