C++ A quick note on compilers rule called AS-IF rule

C++ Coding Tutorial
C

codeguru

Member
Freecoin
295
There is a rule for compilers called AS-IF rule. It means that the compiler, most of the time, has the power to do what it takes to make the code more optimized as long as it doesn't affect the end result -as if it's the same source code-. So the compiler can do any optimizations that do not change the observable behavior of the program.

Let's take few examples -i'll use C language-:

# 1
int x;
x = 0;
// some code that doesn't use x
x = 1;

these are three steps.. we declare x, give it the value 0 then 1. But why? nothig will be different if we defined it with the value 1 from the beginning.

int x = 1;

This is mostly what the compiler will do here because nothing will be noticed when we use x for the first time -all needed is x = 1 when it's used-.

# 2
int x = 20;
for(; x<100; x++) { }

Here too, the end result of this is that x will be 99. So why should it loop a million?! so again the compiler will get rid of the whole loop and replace it with a simple assignment statement.

x = 99; // consider it a 6 9s cuz the post was declined by the super smart AI as it considered it a phone number !

It can execute commands in order that is different from what you have specified if it's better that way.

x += 10;
y += 5;
x += 10;
y += 10;

It can be re-arranged like that
x += 20;
y += 15;

Because it makes no difference to the end result and doesn't affect the rest of the code by any means and can be executed interchangeably.

Commands that has anything to do with I/O operations or a UI thing is not included.

printf("x");
printf("y");

These two print statement can not be executed in different order because it'll give a totally different result.

Most of the time the compiler does its magic and it generates better and more optimized code.

If you defined a variable called x but never used it, it'll be thrown away but what if it may gets used somewhere else? What if you really meant what you typed and want it to be executed the way it is. Maybe another thread is using it, maybe it's shared memory or it's checked asynchronously or any other use case?

There is a type-qualifier in C called vollatile which directs the compiler not to do certain optimizations and to handle this piece of data carefully, in fact the reads and writes for it are done in the order specified in the source code.

#dicode #diaanayel #programming #coding #c #compiler #software
 

Richest Freecoded User

Most Freecoin

freecoded
freecoded
2,513 Freecoin
Davy200
Davy200
590 Freecoin
nathan69
nathan69
424 Freecoin
Laureine
Laureine
415 Freecoin
C
codeguru
295 Freecoin
Tekera
Tekera
263 Freecoin
R
ruthailand
221 Freecoin
A
Akubay
170 Freecoin
smitha
smitha
104 Freecoin
G
Gabby
93 Freecoin
Top