Re: One question of C



drazet wrote:


why the answer is 12 13 13?

[code]

#include <stdio.h>
int x;
int m1(void);
int c1(int x);

int main(void){
int x= 10;

This 'x' shadows the global 'x' while it's in scope. Bad idea.

x++;

Local 'x' is now 11.

c1(x);

Local 'x' is still 11 since c1 gets, and acts on it's own copy of 'x'.
You also discard it's return value.

x++;

Local 'x' is now 12.

m1();

m1 updates the global 'x' and adds 10 to it.
Global 'x' is now 10.

printf("%d\t",x);

This prints the value of the local 'x', i.e., 12.

x++;

And increment it to 13.

c1(x);

Once more c1 gets it's own copy of main's 'x' and increments it by one
and returns that value, which you discard once again.

printf("%d\t",x);

Local 'x' is printed again, i.e., 13.

m1();

Global 'x' is incremented by 10 again.

printf("%d\n",x);

Once more local 'x' is printed, i.e., 13.

return 0;
}

int m1(void){
return (x+=10);

Here 'x' refers to the global object of that name.

}

int c1(int x){
return (x+=1);
}

[code end]


.



Relevant Pages

  • RE: Robby, __int8 limited to: -128 to 127.
    ... And yes an 8bit int cannot hold a value of 256. ... //MIDSB OF MESSAGE ADDRESS IN PAR FLASH ... In order to access the data from my external memory I need a three byte ... and increment the A0 value from 1 to 2. ...
    (microsoft.public.vc.language)
  • Writing Classes
    ... Clock application ... private int hr; //store hours ... public void setTime{ ... //Method to increment the time by one second ...
    (comp.lang.java.programmer)
  • Re: Definition of expression and statement.
    ... The fact that a while loop is recognized ... behavior, e.g., if a is an "int" variable and is initially set to ... The various modifier operators, ... increment and decrement, have TWO uses: ...
    (comp.lang.c)
  • Re: Question about ++
    ... I have got a question about the post increment operator. ... It seems int he code above the ++ is completly disregarded ... Java completely evaluates the right hand side of an assignment before ... Do the assignment, setting i to the right hand side result, 1. ...
    (comp.lang.java.programmer)
  • Re: Pointers gone mad!
    ... Yes, its true Igor, I didn't see it with those values. ... int INCBY, //AMOUNT OF INCREMENTATIONS REQUIRED ... //MIDSB OF MESSAGE ADDRESS IN PAR FLASH ... if {// previous increment overflowed ...
    (microsoft.public.vc.language)