Difference between ++*argv, *argv++, *(argv++) and

2019-03-04 07:07发布

问题:

Currently I am learning C and trying to get my head around these instructions. Are they actually different?

++*argv

*argv++

*(++argv)

*(argv++)

Thanks!

回答1:

It's the postfix increment operator that has higher precedence than the pointer de-reference operator, not the prefix increment. So these two are equivalent:

*p++  *(p++)

The prefix increment has the same precedence as *, so *++p increments the pointer, and is the same as *(++p). Also, ++*p is the same as ++(*p).



回答2:

Take a look at the below code.

main()
    {

       int a[4] = { 10,20,30,40};
       int *argv = a;
       t = ++*argv; 
       printf("%d\n",*argv); /* Here *argv is 11 */
        printf("%d\n",t); /* Here t is 11 because of pre-increment */

       *argv++; /* argv is incremented first ++ has higher priority over "*" */ 
       printf("%d\n",*argv);/* *argv is printed which is 20 */

       *(++argv); /* argv is incremented first ++ has higher priority over "*" */ 
       printf("%d\n",*argv); /* *argv is 30 */

       *(argv++); /* As explained above the same applies here also */
       printf("%d\n",*argv);
    }


回答3:

When you are using pre increment and post increment operators ie ++argv and argv++ in assignments you have to know about the rvalue and lvlue.Like whether the variable value will be incremented first and then get assigned to the LHS or after assigning to LHS the variable value gets incremented.Also the bracket changes the precedence.SO the concepts precedence,lvalue and r value,and rules of pointer increment needs to be understood.



回答4:

Two small examples of incrementing.
Tip: For a better understanding, try to imagine argc as 1 or 2.

Post-increment

In the program below, all arguments are printed including the program name argv[0].

int
main(int argc, char **argv)
{
    while (argc--)
        printf("%s\n", *argv++); /* same as *(argv++) */
}

Pre-increment

In the program below, all arguments are printed except the program name argv[0].

int
main(int argc, char **argv)
{
    while (--argc)
        printf("%s\n", *(++argv));
}

++*argv increments the value *argv.