开发者

Postfix decrement

I have a very simple question.

in this piece of code when will the value of n be decremented?

#include<stdio.h>
void func(int n)
{ 
  //text//
}

int main()
{
  int n=10;
  func(n--);
  return 0;
}

now when func() is called is the value of n decremented when control comes back to main() or is it decremented at that time only but n=10 is passed to func(). Please explain, also if there is a way to chec开发者_C百科k the value then that will be really helpful.


When a function is called, all it's arguments are evaluated (in an implementation-defined order) before the function can start - it's a sequence point. So, after all the arguments are evaluated the function can finally begin.

What this means is that n-- is evaluated and yields the value 10 for the function. At the moment the function has begun n is already 9 but the n parameter of the function hold the value 10.

A simple way to check this:

void func(int n, int *np)
{
    printf("Outside: %d\n", *np);
}

int main(void)
{
    /* ... */
    func(n--, &n);
}


The decrement will happen before the call to func, however func will be passed a copy of the old value still.

Consider the following modification to your program which illustrates this:

#include <stdio.h>

static int n;

void func(int m)
{
  printf("%d,%d\n", n, m);
}

int main()
{
  n = 10;
  func(n--);
  return 0;
}

Prints:

9,10


I think your question is better expressed by this code:

#include <stdio.h>

static int global_n;

void func(int n)
{
    printf("n = %d, global_n = %d\n",
            n, global_n);
}

int main()
{
   global_n = 10;
   func(global_n--);
   return 0;
}

This demonstrates that the function is passed the old value, but the decrement happens before the call.

n = 10, global_n = 9
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜