Krzysztof | 3 Jun 2012 08:38
Picon
Favicon

Is it helpful for a compiler to optimize?

Let's have a below code:

struct st
{
     int iv;
     /*...*/
};

void afun(struct st *stp)
{
     stp->iv++;
     printf("%d\n",stp->iv);
}

Is it helpful for a compiler to do better optimization if I write the 
function as this?

void afun(struct st *stp)
{
     int liv=stp->iv++;

     printf("%d\n",liv);
}

In other words, is it better from optimization point of view to do 
assignments structure members values to local variables then do what you 
need to and then assign them back to member variables?

--

-- 
Regards
(Continue reading)

Krzysztof | 3 Jun 2012 08:59
Picon
Favicon

Re: Is it helpful for a compiler to optimize?

On 06/03/2012 08:38 AM, Krzysztof wrote:
>
> void afun(struct st *stp)
> {
>     int liv=stp->iv++;
>
>     printf("%d\n",liv);
> }
>
Should be: int liv=++stp->iv; of course for equivalence.

--

-- 
Regards
Krzysztof J.

--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo <at> vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Srinivasa T N | 4 Jun 2012 16:09
Picon

Re: Is it helpful for a compiler to optimize?

Why don't you generate the assembly code for both the versions with -s 
and -O<lvl>?

Regards,
Seenu.

On 06/03/2012 12:29 PM, Krzysztof wrote:
> On 06/03/2012 08:38 AM, Krzysztof wrote:
>>
>> void afun(struct st *stp)
>> {
>>     int liv=stp->iv++;
>>
>>     printf("%d\n",liv);
>> }
>>
> Should be: int liv=++stp->iv; of course for equivalence.
>

--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo <at> vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Jesse Ruffin | 3 Jun 2012 10:03
Picon
Gravatar

Re: Is it helpful for a compiler to optimize?


As far as I understand it the compiler's break down the code into
abstract syntax graphs then use a number of graph optimizations to
reduce it into an optimized state. The examples will almost certainly
produce equivalent binary output.

Rather than being concerned about how best to help the compiler
optimize I usually worry about the most understandable way to write
the function. Compilers are really, really good at their job, and the
completely unoptimized version is the one your going to see when you
are debugging -O0 builds.

-Jesse

On 6/3/2012 02:38, Krzysztof wrote:
> Let's have a below code:
> 
> struct st { int iv; /*...*/ };
> 
> void afun(struct st *stp) { stp->iv++; printf("%d\n",stp->iv); }
> 
> Is it helpful for a compiler to do better optimization if I write
> the function as this?
> 
> void afun(struct st *stp) { int liv=stp->iv++;
> 
> printf("%d\n",liv); }
> 
> In other words, is it better from optimization point of view to do 
> assignments structure members values to local variables then do
(Continue reading)


Gmane