0

I faced this problem for the first time and I can't figure it out.

Let's say we have an array and a foreach loop. Something like this:

var v = array(10,20,50);
var i = 0
write(foo(v, v[i++]));

function foo(ref int[] v, name int y){
  foreach(int j in v){
    write(y);
  }
  return y;
}

Am I wrong or something is not gonna work here? I mean, every time I will loop thru the foreach I will evaluate the y (by name) so, being v[i++] I will increase the value of my i variable by one.

  1. So first step y = v[0] so write(10) then i++ (i=1).
  2. Second step y = v[1] so write(20) then I increase i by one (i=2).
  3. Third and last step y = v[2] so write(50) and i++ again, which now equals to 3.

Now, what value should it return?! If I evaluate again y, I can't do y = v[3] cause I go out of bounds. Am I doing anything wrong? Should I just evaluate y once, before the foreach loop? There must be something with the foreach I'm not taking in account when calling parameters by name.

Dunno, I'm a bit confused.

Thanks in advance!

joeguarino
  • 1
  • 1
  • 2
  • Please at least tag with relevant programming language – Paul R Jun 16 '13 at 16:43
  • Hey @PaulR sorry, I wasn't talking about a specific language, but just pseudocode. I don't think you can pass two parameters by reference and by name at the same time, as the foo() function does. It's for educational purposes only, not willing to implement it in an actual program. – joeguarino Jun 16 '13 at 21:30
  • There's a `language-agnostic` tag if you really do want to keep this independent of any particular programming language. – Paul R Jun 16 '13 at 21:33

0 Answers0