multiple '++' working in variables, and pointers

后端 未结 4 617
悲&欢浪女
悲&欢浪女 2021-01-25 20:25

This is what I think the ++ operator does

  1. a++; // a+=1 after calculating this line
  2. ++a; // a+=1 before calcuating this lin
4条回答
  •  囚心锁ツ
    2021-01-25 20:46

    You're not supposed to do more than one increment in arguments to a function.. because the order they can be evaluated in is ambiguous. The result of such code is undefined.

    Meaning: printf("%d,%d,%d,%d\n",a++,a++,++a,++a); Should be written as

    a++; a++;
    ++a; ++a;
    printf("%d, %d, %d, %d\n", a, a, a, a);
    

    Try and fix that first and see if the results are still confusing.

    More generally, you should only have one increment between a pair of sequence points.

    Edit: Chris is right, there's no point writing four increments in the middle of nowhere. To better answer your question: For a function void f(int) and void g(int), with int a=0,

    f(++a) = f(1);
    f(a++) = f(0);
    g(++a, ++a) = g(???); // undefined!
    

    So, increment at most once in the argument to a function.

提交回复
热议问题