R.O.S.S
R.O.S.S

Reputation: 615

Forward use of function parameter

I have remembered now that I saw something like this in C:

void foo(int bar; char baz[bar]) { ... }

I don't remember its name or the valid syntax and I wonder if it's available in C++ too?

Upvotes: 0

Views: 67

Answers (3)

Holt
Holt

Reputation: 37626

Actually, there is some "Forward use of function parameter" in C++, but not what you are talking about.

Since C++11, you can do stuff like this to deduce type of parameters (or return type) using previous parameter:

template <typename T>
auto get (T const& t, size_t i) -> decltype(t[i]) { }

Or:

template <typename T>
void set (T &t, size_t i, decltype(t[i]) const& v) { }

Maybe I am completely off, but since you did not remember exactly what you saw, I thought this might have been stuff like this.

Upvotes: 0

bolov
bolov

Reputation: 75727

For starters, char baz[10] when used as a parameter declares a pointer, not an array, so 10 is completely ignored. This is called array decay to pointer and it's an unfortunate inheritance from C.

Considering you weren't asking strictly about array size, and expanding your question to any use of a previous parameter, the case would be default arguments. E.g.

void foo(int a, int b = a);

And here the answer is again no, it is not valid.

See this answer: https://stackoverflow.com/a/1880877/2805305 for standard justification.

Upvotes: 2

Jack
Jack

Reputation: 133597

No, that's not possible according to the standard, since you are dynamically passing the size of the array to the function, unless there is some special compiler extension that I'm missing.

What you can do is to specify it as a template argument and let the deduction do its work, eg:

template<size_t size>
void foo (char (&a)[size])
{
   for (size_t i = 0; i < size; ++i)
     cout << a[i] << endl;
}

int main()
{
    char a[] = {'a','b','c','d','e'};
    foo(a);
    return 0;
}

Or, since you are working with C++, use an std::array or std::vector and iterators.

Upvotes: 3

Related Questions