You are expected to compare the source code and assembly code for the following
ID: 3602827 • Letter: Y
Question
You are expected to compare the source code and assembly code for the following C code. (You can get the assembly code with usually the –s flag). Can you see any optimizations that can be done on the assembly code?
int a=1, b=2, c=3;
int proc1 (int a, int b, int c)
{
if (a > 0)
return b c;
else
return b + c;
}
int main()
{
int w, x, y;
w = proc1 (a, b, c);
switch (w) {
case 0: x = 3; break;
case 1: x = 4; break;
case 2: x = 7; break;
default: x = 9; break;
}
y = w + x;
return 0;
}
Report:
Please include your (wellcommented) assembly code and your explanation of what this program does and how the assembly code can be optimized. Include your test results with several screenshots.
Explanation / Answer
int proc1 (int a, int b, int c)
{
if (a > 0)
return b c;
else
return b + c;
}
this can be changed as
a = a>0? b-c: b+c . // ternary operator will be faster than if/else statement
return a
After analyzing the switch statement i found a logic to replace the switch statement
switch (w) {
case 0: x = 3; break;
case 1: x = 4; break;
case 2: x = 7; break;
default: x = 9; break;
}
replacement
x = (w==0||w==1) ? 2 + pow(2, w): (w==2)?7:9 // this will replace the whole switch statement and make the code faster
Explanation
case 0: value is 3
3 can be writtern as 2 + 1 ==> 2 + 20
case 1: value is 4
4 can be written as 2 + 2 ==> 2 + 21
case 2 and default case are handled directly in the ternary operator
switch case is more complex
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.