A call function that has a static field twice in one expression

To make the question clear, I wrote some test codes:

#include <stdio.h>
#include <string.h>

char *foo(int a) {
    printf("%d\n", a);
    static char string[2];
    string[0] = a > 0? '1' : '0';
    string[1] = '\0';
    return string;
}

int main(void) {
    printf("%s\t%s\n", foo(1), foo(0));
    return 0;
}

Running the code gives the output as follows:

0
1
1       1

I have two questions: 1. Why is 0 printed to 1? in the main printf function does the second foo run before the first? Whether this is a specific behavior or by accident. 2. Why is the final result 1, 1? Expected result should be 1, 0.

+3
source share
3 answers

The order in which the arguments are evaluated depends on the implementation - your compiler simply implements it this way

EDIT: according to your second question, you are using a static buffer. This means that it is separated by foo () calls - that is, both foo () calls return the same pointer.

, 0, 1. , foo(), , 1 - ( static == shared).

, , , .

+2

, foo (1) foo (0) , C. foo (0), foo "0" . foo (1), "1". . , .

0

:

printf:

printf("%s\t%s\n", foo(1), foo(0));

It calls foo()first with help 0, then 1. With each call, the address is Stringreturned and stored in a variable. Because String- static, the address does not change. Upon completion of the call, he comes to printfprint the contents String, the last change of which occurs with String(after the call foo(1)). The same address means the same value, means that the output:

0
1
1       1
0
source

All Articles