C++ Lookup of i changed for ISO

自闭症网瘾萝莉.ら 提交于 2019-12-02 09:42:31

问题


I have the following code for a dictionary.

void Dictionary::translate(char out_s[], const char s[])
{

for (int i=0;i<numEntries;i++)
{
   if (strcmp(englishWord[i], s)==0)
       break;
}
if (i<numEntries)
strcpy(out_s, elvishWord[i]);

which gives me the error name lookup of i changed for iso and mentions that the code will be accepted if i use -fpermissive. If i try and initialize the variable outside the for loop it generates a whole load of errors.

Any ideas?

Thanks in advance.


回答1:


Not "for iso" (perhaps read the entire error message...), but for ISO C++. The problem is that the scope of the i variable is only the for loop (since its definition is inside the initialization of the loop). Since it seems you want to use it outside the loop, declare it like so:

int i;
for (i = 0; i < foo; i++) {
    // ...
}

do_safe_stuff_with(i); // valid



回答2:


When you do e.g.

for (int i=0;i<numEntries;i++)

then the variable i is local to the loop only, you can't really use it outside the loop.

If you want to use i outside the loop, then you need to declare it outside the loop:

int i;
for (i=0;i<numEntries;i++)



回答3:


i is declared in the for loop condition clause. it is not visible at the if clause after for loop.

try:

int i = 0;
for (;i<numEntries;i++)
{
   if (strcmp(englishWord[i], s)==0)
       break;
}
if (i<numEntries)


来源:https://stackoverflow.com/questions/16468911/c-lookup-of-i-changed-for-iso

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!