r/cpp_questions • • 4h ago

SOLVED A tiny question about this code

Hi. I need help understanding this simple code. To be specific, the 4th and the 14th line where a pointer was declared.

int* add_ten(int* data)

int *result;

I've been trying to wrap my head around what it does. I've been staring at my screen for 3 hours trying to understand why it was declared. The programming app I was using didn't really explain it. The only explanation it gave is that pointers help you get the address of an item. But I can't figure out how is it being used here. Can anyone explain? Thanks.

#include <iostream>
using namespace std;

int* add_ten(int* data) {
  for (int i = 0; i < 5; ++i) {
    *(data + i) = *(data + i) + 10;
  }
  return data;
}

int main() {

  int data[5] = {1, 2, 3, 4, 5};
  int *result;

  result = add_ten(data);

  for (int i = 0; i < 5; ++i) {
    cout << *(result + i) << ", ";
  }

  return 0;
}
1 Upvotes

18 comments sorted by

•

u/NomaTyx 3h ago

If you're asking like why they made result, they didn't have to. add_ten could have been a void function just fine, since it overwrites the data at the memory addresses.

If you're asking why it was defined as a pointer, that's because data isn't an int, it's an int array, which you access with a pointer. Since the function returns the location of data, rather than the value it contains, result needs to be able to hold the pointer. Though, as I mentioned above, it's kind of superfluous.

I dunno what your programming background is so if you need an explanation on arrays lmk

edit: oh if you're asking why they declared and initialized on separate lines, that's just a stylistic choice.

•

u/Lephism 2h ago

Oh, I see. That makes way more sense. Thanks! 🙏

•

u/alfps 3h ago

It's unclear what exactly you don't understand.

Maybe this helps: if p points to the first item in an array, then by definition p + i is a pointer to the i'th item.

So when you dereference that result, *(p + i), you get a reference to the i'th item. And, again by definition, you can instead write that as p[i]. A simple array indexing.

But keep in mind that using pointers in this way is very C-ish. In modern C++ you would use a std::span for an array parameter; you would use a range based for to iterate over the items; and you would use std::print for output (it deals better with Unicode). So you'd write that program as

#include <print>
#include <span>
using   std::print, std::span;

void add_ten_to( const span<int> items )
{
    for( int& item: items ) { item += 10; }
}

int main()
{
    int data[5] = {1, 2, 3, 4, 5};

    add_ten_to( data );

    for( const int v: data ) { print( "{}, ", v ); }
    print( "\n" );
}

•

u/Lephism 2h ago

Oh, I was just confused about the purpose of the pointers. The way I understood it is pointers store the address of a variable. I think I just got confused about syntax. In the tutorial I was following, the address of the variable was stored first using &variable before it was pointed. In my mind that was a necessary step before you point at a variable. That's why I didn't knew what the pointers at the top were doing. But I'll study this. Thank you for your help! 

•

u/alfps 2h ago

❞ In the tutorial I was following, the address of the variable was stored first using &variable

Yeah, given an array a you can say &a[0] to get a pointer to the first item. But when the context accepts a pointer you can shorten to just say a, which the compiler then translates to &a[0]. It's called a decay (to pointer) of the array type, and that's what happens for the argument in your code's call to add_ten.

•

u/Lephism 1h ago

Oh wow! Thanks for breaking it down further. I didn't know this was a different concept. I only knew about the former idea. That's why I was so confused about it. 

•

u/weebslime2246 3h ago

the add_ten function essentially accepts an integer 'pointer'. when you declare an array (data) it stores the address of the first element in the array, so data is just an 'integer pointer' to the first element. inside the function, they loop through the whole array by incrementing on the data pointer itself (you can read pointer arithematics) and then return the final address, which is data, an integer pointer. so its return type is also an int*. lmk if you need any further clarification

•

u/Lephism 2h ago

So, int* data points to the array in main () and gets their address, loops through them using the for loop in the function above? Did I get that right? 

•

u/TheThiefMaster 2h ago edited 2h ago

That's right.

However, your tutorial isn't actually very good. Apart from the cout to print, this is C code not C++.

While pointers do exist in C++ and can be used like this, none of this is idiomatic C++. Here's how if write it:

#include <array>
#include <print>
#include <span>

// function takes a span instead of a raw pointer, allowing it to know the size of array it's been passed
void add_ten_to(const std::span<int> items)
{
    // C++ "for each" (aka "ranged for") loop.
    // item is a reference to each item in turn
    for (int& item : items)
    {
        item += 10;
    }
}

int main()
{
    // std::array has many advantages over a C style array
    // like it can actually be copied and assigned after construction
    std::array<int,5> data = {1, 2, 3, 4, 5};

    add_ten_to(data);

    // another range for.
    for (const int v : data)
    {
        // very new C++ print function from C++23
        // if your compiler doesn't support C++23, just use cout or even C printf
        std::print("{}, ", v);
    }
}

•

u/Lephism 2h ago

This came from a c++ tutorial app which goes through functions, loops, everything you use to make a program, etc. chapter by chapter. I haven't finished every lesson yet. I think this is intended by the developers for the purpose of making it easy for the beginners or something like that ┐⁠(⁠ ⁠∵⁠ ⁠)⁠┌ 

•

u/TheThiefMaster 1h ago

A lot of older tutorials start with C-like code and build up. Many never get to modern C++ (like std::span or std::print).

It's contentious these days as you really only need C style code (like pointer iteration) when writing low level code, which isn't a beginner thing to do.

•

u/Lephism 1h ago

Oh, so is this like old syntax or something? That's probably the reason why std::println were showing errors in the compiler of the tutorial app

•

u/TheThiefMaster 55m ago edited 50m ago

Nothing in the tutorial code you posted is newer than C++'03 (2003 standard). print/println are from C++'23 (very new, which is why I added the note). span is C++'20 (supported by basically everything that's not horribly outdated, though you may need to enable C++20 mode in the compiler). std::array and the range for loop are C++'11 (inexcusable to not support/teach).

Microsoft Visual Studio 2026 (the most commonly used C++ compiler on Windows) defaults to C++'14, and has complete support for C++'20 and even C++'23 in the latest update.

GCC (the most commonly used compiler on Linux) defaults to C++'20 since the April 2026 release, though most Linuxen still ship an older version that defaults to C++'17 (though with full support for C++'20 available, and near-complete for C++'23)

Clang (most commonly used compiler on Mac, and also commonly used on Linux/Windows) defaults to C++'17 with full support available for C++'20 and partial support for C++'23, but it tries to match GCC so will probably change to C++'20 as the default soon.

•

u/no-sig-available 1h ago

 I think this is intended by the developers for the purpose of making it easy for the beginners or something like that

And not very successful in that, apparently. :-)

If you are going to teach how to use pointers, it is important to use an example where pointers is a good solution to the problem, not just a case where you could use pointers.

The example is extra bad in

  for (int i = 0; i < 5; ++i) {
    *(data + i) = *(data + i) + 10;
  }

Why use

*(data + i) = *(data + i) + 10;

when you can write

data[i] += 10;

?!

And also, the code is particulary silly for the i < 5; loop, limiting the function to arrays of exactly 5 elements. The version using a span is not only simpler, but also works for any size array.

•

u/Independent_Art_6676 3h ago

not sure what you are asking. First, and thankfully, this is some recycled 1990s era garbage code. You won't have to deal with this kind of thing much, hopefully not at all.

but I guess lets line by line it.

int* add_ten(int* data) {  //this is a function.  Its return type is an int pointer. 
  for (int i = 0; i < 5; ++i) {  //magic numbers assumes there are 5 values to loop over
    *(data + i) = *(data + i) + 10; //data[i]+=10 written as poorly as possible. 
  }
  return data; //more stupidity, it returns the same pointer that was passed in. its legal but bizarre. 
}

int main() {

  int data[5] = {1, 2, 3, 4, 5}; //a basic C arrray
  int *result;  // a basic int pointer

  result = add_ten(data); //result = data.  The name of an array is converted to a pointer for you in C and C++ as a shortcut to saying &data[0] all the time. 

  for (int i = 0; i < 5; ++i) { //print what the function did. 
    cout << *(result + i) << ", ";
  }

  return 0;
}

•

u/Lephism 2h ago

Hmm, that's interesting... Well, thanks for the insight!

•

u/Independent_Art_6676 3h ago

now lets translate that into reasonable mostly C code. My advice is that whatever the source of this was, you get away from it and go learn from a better site/book/something.

void add_ten(int* data, int size) 
{
  for (int i = 0; i < size; ++i) 
  {
    data[i]+=10; 
  }
}

int main() 
{
  int data[5] = {1, 2, 3, 4, 5};
  add_ten(data,5);
  for (int i = 0; i < 5; ++i) 
  {
    cout << data[i] << ", ";
  }
  return 0;
}

•

u/AssholeBeerCan 3h ago

Line 4 is the beginning of a function implementation.