0

I can't seem to figure out what is causing the following error:

trainLine.cpp:108: error: name lookup of ‘i’ changed for new ISO ‘for’ scoping

trainLine.cpp:98: error: using obsolete binding at ‘i’

Here is the code that is causing the error:

int main()
{
  pthread_t tidArray[NUM_TRAINS];
  Train* trainArray[NUM_TRAINS];

  for (int i = 0; i < NUM_TRAINS;  i++)
    trainArray[i] = new Train(TRAIN_NAME_ARRAY[i], TRAIN_TRANSIT_TIME_MSECS[i]);

  int trainInd = 0;

  pthread_create(&tidArray[i], NULL, initiallyNorthernly,(void*)&trainArray[i]);

  pthread_create(&tidArray[i], NULL, initiallySouthernly,(void*)&trainArray[i]);

  for  (int i = 0; i < NUM_TRAINS;  i++)
    trainArray[i] = NULL;

  pthread_join(tidArray[i], (void**)&trainInd);

  return(EXIT_SUCCESS);
}

I apologize in advance, but I am very new to C/C++ and nothing is popping out as wrong to me. Possibly not placing brackets around for loop statements? Thanks in advance for any help.

Community
  • 1
  • 1
SciGuy
  • 59
  • 1
  • 6
  • 3
    What do you expect `i` to be outside of those loops? – TartanLlama May 22 '15 at 11:32
  • 1
    you're probably forgot braces that create compount statement: `for(...) { trainArr[i] = ...; pthread_create(...); }` Also, why do you create two threads in the same object `tidArray[i]`, it is incorrect – myaut May 22 '15 at 11:33
  • 1
    Yes, "not placing brackets around for loop statements", as you suspect. (But didn't attempt to do anything about, apparently.) – molbdnilo May 22 '15 at 11:40
  • http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar May 22 '15 at 11:44
  • It strikes me as interesting that you're new enough to C to not know about enclosing statements in `{`/`}` compound blocks for loops (and other control structures, I guess), but you're diving into pthreads already? It seems that you would have done at least one example program between "hello world" and multi-threaded C. – Michael Burr May 23 '15 at 17:03

2 Answers2

1

Your variable i exists only inside the for-loop, but you're trying to use it outside the loop.

Something like this could solve the problem, without altering the effect of the code:

  // ...
  int i = 0; // i is now accessible outside the loop as well
  for  (;  i < NUM_TRAINS;  i++)
    trainArray[i] = new     Train(TRAIN_NAME_ARRAY[i],TRAIN_TRANSIT_TIME_MSECS[i]);

  // use i, which is equal to NUM_TRAINS at this point
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

In the line:

pthread_join(tidArray[i], (void**)&trainInd);

you're referencing i, which is out of scope. I'm guessing you actually wanted this to be part of a loop, e.g.

for (int i = 0; i < NUM_TRAINS; ++i)
    pthread_join(tidArray[i], (void**)&trainInd);
Paul R
  • 208,748
  • 37
  • 389
  • 560