Confusing C code, does someone explain this to me?

The order of evaluation is important, so what is called non-referential transparency?

int i = 1;
int counter(){
     i = i + 1;
     return i;
}
int foo(int i, int j){
    return i*2 + 3*j;
}
int main(){
   printf("%d", foo(counter(), counter()));
}
+3
source share
8 answers

I assume that you can keep in mind that the order of evaluation of function parameters is not standardized in C. Since it counter()returns a different result for each call, and the result foo(2, 3)is different from the result foo(3, 2), compiling and executing this code can give different results on different platforms.

, . [] ( : . , , .) [/Update]

+10

, . , , . C " "

, , (C99 §3.4.4/1).

, " " - , , , , .

, , - .

, , ; .

+7

, .

+6

counter() , i . . , 1 !

+4

, , , .

C99 (6.5/3 ):

, ( -(), &, ||,?: ), , , .

, foo() . , 2 counter() . - :

  • ( , , )
  • , .

, , , (, , ), : .

, ( ), - , foo(). , , ( , , ):

#include <stdio.h>

int i = 1;

int counter1(){
     i = i * 3;
     printf( "counter1()\n");
     return i;
}

int counter2(){
     i = i * 5;
     printf( "counter2()\n");
     return i;
}

int foo(int i, int j){
    return i + j;
}

int main(){
   int x;
   for (x=0; x<2; ++x) {
       printf("%d\n", foo(counter1(), counter2()));
   }

   return 0;
}

, ( ):

1:

counter1()
counter2()
18
counter1()
counter2()
270

2:

counter1()
counter2()
18
counter2()
counter1()
300

3:

counter2()
counter1()
20
counter2()
counter1()
300

( ), - , , , .

, "", , ( ), / , , .

, , .

, , - , , .

+3

, , , , foo 2,3 3,2.

+1

Code Clown, . "".

C . , foo , .

0

foo() . , . , .

C , , :

(there are many ways to make a link function opaque, they are more common)

Here, subsequent calls to counter () lead to different values, so they are opaque by reference.

0
source

Source: https://habr.com/ru/post/1754687/


All Articles