Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are given the following C-like code. int foo(int *p) {. *p = 1; return 2;} i

ID: 3822159 • Letter: Y

Question

You are given the following C-like code. int foo(int *p) {. *p = 1; return 2;} int bar(int *p) {*p = 3; return 4;} int main() {int x = 10, y; y = x + foo(&x;) + bar(&x;);//Statement A} There are at least three ways to evaluate the expression in statement A that results in variable y taking three different values. Briefly elaborate the three ways and state the value of y after each way of evaluation. Write a function in C that has no functional side effect but is not referential transparent. Your function cannot have any print statements. State the semantics of your function. In C or C++, evaluating the expression a = a++ produces undefined behavior. Give a reason to justify this design.

Explanation / Answer

(a)

The statement A is:

y = x + foo(&x) + bar(&x);

The value of y depends on the orders in which y, foo(&x) and bar(&x) are executed.

i) Let the order be foo(&x),bar(&x),x

foo(&x) is called and it returns 2 but x becomes 1.

bar(&x) is called and it returns 4 but x becomes 3.

x is 3

So y = 3+2+4 = 9

ii) Let the order be foo(&x),x,bar(&x)

foo(&x) is called and it returns 2 but x becomes 1.

x is 1

bar(&x) is called and it returns 4 but x becomes 3.

So y = 1+2+4 = 7

iii) Let the order be x,foo(&x),bar(&x)

x is 2

foo(&x) is called and it returns 2 but x becomes 1.

bar(&x) is called and it returns 4 but x becomes 3.

So y = 2+2+4 = 8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote