-2

I saw the following line of code in C++. I have trouble understanding it. I hope that I can get some help here.

// Example program
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a[] = {1,2,3,4};
    cout<<*a+1<<;
    cout<<a[1];

}

Question: I don't understand how *a+1 works. It seems pretty unintuitive - are we adding 1 to the array here?

Borgleader
  • 15,826
  • 5
  • 46
  • 62

3 Answers3

0

In the expression *a + 1, the array a is evaluated in pointer context, so it points to the first value in the array.

Next, *a dereferences that pointer (meaning it gets the value the pointer points to), and that gives you the first element in the array which is 1.

Finally, 1 is added to that value and printed, so it outputs 2.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

First of all this statement

cout<<*a+1<<;
          ^^^^

is syntactically wrong.

I think you mean something like

cout << *a+1 << endl;

Expression *a is equivalent to a[0]. So you could write instead

cout << a[0] + 1 << endl;

Take into account that semantically a[0] + 1 is not the same as a[1] though applied to your example the both expressions will yield the same result.:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

To understand the expression *a+1 you should consider the operator priority:

the dereference * has higher priority, so a (the name of an array is also the pointer to the first element) is dereferenced, giving the value 1

Then, 1 will be added to the value.

operator priorities are describe here http://en.cppreference.com/w/cpp/language/operator_precedence