Why is a global variable different from a local variable in this function?

Here I have a function named max(a,b)to get the maximum number of two. And I found that the value of the variable aand busing printf()is different after execution

printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);

when aand bare equal Global variablesand Local variables. Below is my code:

#include<stdio.h>

int max(int a,int b)
{

    if(a>b)
    {
        //printf("In func max():%d %d \n",a,b);
        return a;
    }
    else {
        //printf("In func max():%d %d \n",a,b);
        return b;
    }

}
void jubu_test(void)
{
    int a=1;
    int b=2;    
    printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);  //a=2,b=3
}
int c=2;
int d=1;
void quanju_test(void)
{
    printf("maxcd()=%d  c=%d d=%d \n",max(c++,d++),c,d);    //c=2,d=1
    c=2;
    d=1;
    int f=max(c++,d++);
    printf("maxcd()=%d after max: c=%d d=%d \n",f,c,d);     //c=3,d=2
}   
int main(int argc, char** argv)
{
    jubu_test();
    quanju_test();
}

The result that I get on my computer:

maxab()=2 after max: a=2 b=3
maxcd()=2  c=2 d=1
maxcd()=2 after max: c=3 d=2

My question is: why in the second output are a and b their initial value and why is the third output equal to + 1 and b + 1? Why, when a and b are global variables, the value of a and b is only displayed on first run max(a++,b++)? Why, when a and b are local variables, does it not matter?

Thank! (using gcc 5.3.0 on windows 10)

+4
2

printf(... max(a++,b++),a,b); undefined ( ++) undefined ?.

a++ a, b++ b. , , .

Undefined = . , - , -, ..

undefined , C11 6.5/2:

, undefined.

(a - , .. a++ . a .)


, , , , . , - :

int func (void)
{
  static int x=0;
  x++;
  return x;
}

printf("%d %d", func(), func());

1 2, 2 1, , . , . .

, , , , , undefined.

+5

, . C . , .

+3

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


All Articles