简体   繁体   中英

C++ pointer . I want to know about the logic

i have a question on pointer concept which i could not find a logical answer to

#include<conio.h>
#include<iostream.h>
void main()
{
    int arr[10];
    clrscr();
    cout<<*arr+5 - *arr+3;
    getch();
}

even if i assign arr[0]=10; (or any other value)

the compiler gives answer 8 but how . I can not see(understand) how operator precedence and associativity does solve it.

I will be grateful to you.

Because of *arr - *arr is 0 and 5 + 3 is 8.

The result you may be expecting is the result of:

cout<<(*arr+5) - (*arr+3);

编译器给出答案8,因为该操作仅等效于:(* arr-* arr)+ 5 + 3 =8。如果要将标量添加到指针,然后获取引用的值,则必须使用括号* (arr + 5)。

If you look at the precedence table, for example here:

http://en.cppreference.com/w/cpp/language/operator_precedence

then you'll notice that the dereference operator (*) has higher priority than addition/subtraction (+/-) operators (they are in group no. 3 and 6 respectively). This is why the first operation that is performed is getting the value that the arr variable is pointing to, ie this part:

*arr

After this, the addition/subtraction is performed. The value that arr is pointing to doesn't matter since it gets reducted anyway.

This is how you should read this expression:

(*arr) + 5 - (*arr) + 3

and (*arr) - (*arr) is 0, no matter what value it points to.

EDIT: What I've written above is apparently true in your case and your compiler, but look at the @Konrad Rudolph comments to this answer.

And, if you are curious, how the compiler knows if, for example, the '*' should be treated as multiplication or dereference operator: it resolves this problem by looking at the number of arguments - if there's only one, than it's derefence, and if there are two, then it's multiplying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM