0
int * decrementArrayElements(int numbers[], int size){
    for (int &x: numbers)
    {
        x = x-1;
    }
    return numbers ;
}

well as mentioned am trying to dec val of each array ele by 1 by range based for

If I try normal for loop it works

int * decrementArrayElements(int numbers[], int size){
    // int n= sizeof(numbers)/sizeof(numbers[0]);
    for (int i=0; i<size; i++)
        numbers[i]=numbers[i]-1;
    return numbers;
}

so could pls explain me the reason behind this

2
  • 4
    That code doesn't compile. The first for statement doesn't work, because the compiler doesn't know how many elements there are. That's why you should be using std::vector. Commented Aug 8, 2023 at 1:42
  • to dec val of each array ele - you don't seem to respect SO users that have to read your abbrevations. Commented Aug 8, 2023 at 1:51

1 Answer 1

2

The parameter int numbers[] is actually a pointer, not an array. Range-based loops do not work on pointers.

If you have a C-style array that for whatever reason you need to pass safely to a function, you can use a function template. This allows the compiler deduce the array size from its type.

#include <cstdint>
#include <iostream>

template <std::size_t size>
int * decrementArrayElements(int (&numbers)[size])
{
    for (int &x : numbers) --x;
    return numbers;
}

int main()
{
    int numbers[] = { 1, 2, 3, 4 };
    decrementArrayElements(numbers);
    for (int x : numbers) std::cout << x;
}

Outputs:

0123

In this case the pattern of returning a pointer probably isn't all that useful. It's more likely to be abused. I would lean towards making the function void.

You may want to consider using std::array instead, which has better encapsulation and (unlike C-style arrays) has copy semantics consistent with other types.

#include <array>
#include <cstdint>
#include <iostream>

template <std::size_t size>
std::array<int, size>& decrementArrayElements(std::array<int, size>& numbers)
{
    for (int &x : numbers) --x;
    return numbers;
}

int main()
{
    std::array<int, 4> numbers = { 1, 2, 3, 4 };
    decrementArrayElements(numbers);
    for (int x : numbers) std::cout << x;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.