Error name lookup of j changed for iso for scoping fpermissive

The error is: In function ‘int returnShortestWeightedBranch(std::vector<route, std::allocator >*)’: error: name lookup of ‘jj’ changed for ISO ‘for’ scoping note: (if you use ‘-

The error is:

In function ‘int returnShortestWeightedBranch(std::vector<route, std::allocator<route> >*)’:
error: name lookup of ‘jj’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)

The code is:

for (int i = 0; i< routeVector.size(); i++)
        {
            if (routeVector[i].exitPoint == exitPointDetailsVector[preserveL].exitPoint)
            {
                cout << "n-----------parent: " << routeVector[i].exitPoint;
                branch obj;
                obj.connectedExitPoint = exitPointDetailsVector[preserveI].exitPoint;
                routeVector[i].selectedBranchesVector.push_back (obj);

                for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);
                {
                    cout << "n-----------branch: " << routeVector[i].selectedBranchesVector[jj].connectedExitPoint;
                }
            }
        }

What can be the problem here?

EDIT 1:

I changed the following:

for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

to:

int jj;
for (jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

and now it is working!! I fail to understand the REASONS.

asked Jul 2, 2011 at 10:27

Aquarius_Girl's user avatar

Aquarius_GirlAquarius_Girl

21.3k62 gold badges219 silver badges397 bronze badges

2

You have a semicolon at the end of the inner for statement. That ends the scope of jj there, so it is not visible inside the block.

Edit
You have solved the scope problem, but still have your for loop executing just

<nothing>;

Remove the semicolon after the parenthesis!

answered Jul 2, 2011 at 10:36

Bo Persson's user avatar

Bo PerssonBo Persson

89.8k31 gold badges144 silver badges201 bronze badges

0

for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

This line ends with a semicolon! It shouldn’t :)

answered Jul 2, 2011 at 10:33

Kornel Kisielewicz's user avatar

0

Some compilers may not accept the use of the variable ‘jj’ after the for loop is ended. Since the variable is declared inside the for loop, it is destroyed right after it is executed. Thus when you declare your iteration variable outside the for loop it remains there for further use.

In reality it doesn’t work like that and that’s why you can force the compiler to ignore the error by adding ‘-fpermissive’.

answered Sep 4, 2013 at 18:31

Matheus Z's user avatar

Matheus ZMatheus Z

811 silver badge2 bronze badges

False: for(...;...;...;);

True: for(...;...;...;)

You shouldn’t use a semicolon, ;

joe_young's user avatar

joe_young

4,0682 gold badges26 silver badges38 bronze badges

answered Jan 27, 2016 at 16:14

Emre q's user avatar

rennnorb

19 / 10 / 6

Регистрация: 28.05.2014

Сообщений: 140

1

07.07.2014, 16:54. Показов 18640. Ответов 3

Метки нет (Все метки)


Компилятор ругается :
main.cpp: In function ‘int main(int, char**)’:
main.cpp:56:18: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
cout<<buff[i]<<» «;
^
main.cpp:56:18: note: (if you use ‘-fpermissive’ G++ will accept your code)

на код :

C++
1
2
for(int i=0; i<size; i++)
            line[i]=buff[i];

Помогите!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

07.07.2014, 16:56

2

Лучший ответ Сообщение было отмечено rennnorb как решение

Решение

Ты или i используешь вне цикла или она где-то уже объявлена.



1



19 / 10 / 6

Регистрация: 28.05.2014

Сообщений: 140

07.07.2014, 17:00

 [ТС]

3

Спасибо!



0



zibertscrem

3 / 3 / 4

Регистрация: 03.07.2014

Сообщений: 19

07.07.2014, 17:08

4

По сообщению в ошибке это вывод cout<<buff[i]<<» «; вне цикла с необъявленной i.
Если i была объявлена внутри цикла, то снаружи она уже не доступна(доступна она только в старом стандарте C). Поэтому, если делаете вывод сразу при заполнении, то вам нужно написать вот так:

C++
1
2
3
4
5
for(int i=0; i<size; i++)
{
            line[i]=buff[i];
            cout<<buff[i]<<" ";
}



0



В. Напишите программу, которая «выдает» слова, которые вам не нравятся; то есть вы читаете словами cin и снова печатаете их на cout. Если слово входит в число определенных вами, вместо этого слова вы пишете BLEEP. (книга Страуструпа с ++)

Вот код, который я написал:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
vector<string> disliked;
disliked.push_back("Broccoli");
disliked.push_back("Carrots");
disliked.push_back("Tomatoes");
disliked.push_back("Asparagus");

vector<string> words;
string word;
while (cin >> word) {
words.push_back(word);
}
for (int i = 0; i < words.size(); ++i) {
cout << words[i] << "t";     //i used it to see if the program was working
}
for (int j = 0; j < disliked.size(); ++j) {
cout << disliked[j] << "t";
}
for (i = 0; i < j; ++i) {
if (words[i] == disliked[j]) {
cout << "BLEEP";
}
else {
}
}
}

Я думаю, что проблема возникает из-за моего последнего цикла for, но я не понимаю, что делать.

Вот ошибка, которую я получил:

bleep.cpp: In function ‘int main()’:
bleep.cpp:27:8: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
bleep.cpp:27:8: note: (if you use ‘-fpermissive’ G++ will accept your code)
bleep.cpp:27:19: error: name lookup of ‘j’ changed for ISO ‘for’ scoping [-fpermissive]

0

Решение

Проблема в:

for (i = 0; i < j; ++i) {
if (words[i] == disliked[j]) {
cout << "BLEEP";
}
else {
}
}

Здесь вы используете i а также j не объявляя их. Предыдущие объявления имеют только ту область блока, в которой вы декларируете. Либо вам нужно переопределить их, либо, если вы хотите использовать предыдущие значения, объявите их выше первого for петля.

9

Другие решения

Вы объявили переменную я а также J в цикле for, следовательно, из-за проблемы с областью действия вы не можете получить доступ к переменным в другом цикле for.

Из того, что я понял, в последнем цикле for вы проверяете, каждое ли слово в слова массив равен одному из слов в нелюбимое массив. Для этого вам нужно использовать два цикла for следующим образом:

for(int i=0; i<words.size(); i++){
for(int j=0; j<disliked.size(); j++){
if(words[i] == disliked[j]){
words[i] = "BLEEP";     //This step replaces the disliked word with "BLEEP"}
}
}

Примечание: если вы объявите int i,j; прежде чем использовать их в циклах, вам не нужно объявлять их снова внутри циклов for.

4

Member Avatar


mike_2000_17

2,669



21st Century Viking



Team Colleague



Featured Poster


9 Years Ago

You are missing the curly braces in this for loop:

    for(int j=0; j<=years; j++)
    cout<<"Enter runs scored by player"<<":"<<i+1<<": ";
    cin>>record[i][j];

You’ll see it better if you space it out and indent properly:

    for(int j = 0; j <= years; j++)
        cout << "Enter runs scored by player" << ":" << i+1 << ": ";

    cin >> record[i][j];

As you see, the cin >> record[i][j]; is outside the scope of the for-loop. The error message is telling you that the variable j is undefined at that point. The reason the error message is weird is because it use to be (before the ISO standard) that the variable declared in the for-loop would exist in the scope enclosing the for-loop (e.g., holding the value it had at the last iteration), this rule has changed and is no longer allowed.

To fix the error, you need this:

    for(int j = 0; j <= years; j++) {
        cout << "Enter runs scored by player" << ":" << i+1 << ": ";
        cin >> record[i][j];
    };

Member Avatar


rubberman

1,355



Nearly a Posting Virtuoso



Featured Poster


9 Years Ago

Mike2K points out a common coding issue — proper scoping of loops. My personal process says «scope everything» — loops, conditionals (if/then/else), etc. IE, place proper brackets around all loops and conditional blocks of code. Then, when you need to add a line to them, they will still be properly constrained! :-)

  • Forum
  • Beginners
  • fpermissive flag?

fpermissive flag?

I’ve been working on a code for an Armstrong problem, but when trying to compile the code, I got this error:

prog4a.cpp: In function ‘int main()’:
prog4a.cpp:42:25: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
answer = getRaiseAndAdd(i);
^
prog4a.cpp:42:25: note: (if you use ‘-fpermissive’ G++ will accept your code)

I tried Googling the -fpermissive flag, but could not find any help on how to prevent it from showing as an error. Any suggestions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

using namespace std;

//Function name: getRaiseAndAdd
//Purpose: Calculate each digit cubed and the sum of the results.
//We are sending in the current number from the loop starting at 100 and
//counting one by one to 999.
//Parameters: &numberInput
//Return value: Result of adding 3 numbers
int getRaiseAndAdd(int &numberInput)
{
int firstNumber, secondNumber, thirdNumber;
int remainder;
int sum;
int firstPower, secondPower, thirdPower;

firstNumber = numberInput / 100;
remainder = numberInput % 100;
secondNumber = remainder / 10;
thirdNumber = remainder % 10;

firstPower = firstNumber * firstNumber * firstNumber;
secondPower = secondNumber *secondNumber * secondNumber;
thirdPower = thirdNumber * thirdNumber * thirdNumber;

return sum = firstPower + secondPower + thirdPower;
}

int main()
{
int answer;
int originalNumber;

for(int i = 100; i < 1000; i++)
originalNumber = i;

answer = getRaiseAndAdd(i);
        {
        //Function name: is_Armstrong
        //Purpose: finding the Armstrong numbers
        //Parameters: answer
        //Return value: 0
        bool is_Armstrong (int answer);
        if(answer == originalNumber);
                {
                cout << "found an Armstrong number " << originalNumber << endl;
                }
        }

return 0;
}

Last edited on

You need to use curly braces in your for loop here

1
2
3
4
for(int i = 100; i < 1000; i++){
originalNumber = i;
answer = getRaiseAndAdd(i);
}

So that the variable i can be used in this part of your code answer = getRaiseAndAdd(i); That is the reason your getting this error

prog4a.cpp:42:25: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
answer = getRaiseAndAdd(i);

Last edited on

Hi,

You can’t have a function declaration there on line 44. remove the type if you meant it to be a function call.

Remove the semicolon from line 45.

In early C++ variable lifetime was different:

1
2
3
4
5
6
7
{
  int Y;
  for ( int X = 0; X < 42; ++X ) {
    // code
  }
// X and Y still exist
} // X and Y go out of scope 

That did change in the (ISO) C++ standard:

1
2
3
4
5
6
7
8
{
  int Y;
  for ( int X = 0; X < 42; ++X ) {
    // code
  }
// X is out of scope; does not exist any more
// Y still exists
} //  Y goes out of scope 

The compiler has a command line option that makes the compiler forget the standard and operate in the early mode. This allows recompilation of legacy code. If it did not have legacy support and be «helpful», then the error would be undeclared identifier ‘i’.

man gcc

and look for «fpermissive» within.
(Does Google treat prefix hyphen as logical NOT?)

Topic archived. No new replies allowed.

Ошибка:

In function ‘int returnShortestWeightedBranch(std::vector<route, std::allocator<route> >*)’:
error: name lookup of ‘jj’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)

Код:

for (int i = 0; i< routeVector.size(); i++)
        {
            if (routeVector[i].exitPoint == exitPointDetailsVector[preserveL].exitPoint)
            {
                cout << "n-----------parent: " << routeVector[i].exitPoint;
                branch obj;
                obj.connectedExitPoint = exitPointDetailsVector[preserveI].exitPoint;
                routeVector[i].selectedBranchesVector.push_back (obj);

                for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);
                {
                    cout << "n-----------branch: " << routeVector[i].selectedBranchesVector[jj].connectedExitPoint;
                }
            }
        }

В чем может быть проблема?

РЕДАКТИРОВАТЬ 1:

Я изменил следующее:

for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

в

int jj;
for (jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

и теперь он работает!! Я не понимаю ПРИЧИНЫ.

02 июль 2011, в 12:38

Поделиться

Источник

4 ответа

У вас есть точка с запятой в конце внутреннего оператора for. Это закрывает область jj там, поэтому она не видна внутри блока.

Изменить
Вы решили проблему с областью видимости, но все же хотите, чтобы ваш цикл for выполнял только

<nothing>;

Удалите точку с запятой после скобки!

Bo Persson
02 июль 2011, в 11:49

Поделиться

for (int jj = 0; jj < routeVector[i].selectedBranchesVector.size(); jj++);

Эта строка заканчивается точкой с запятой! Это не должно:)

Kornel Kisielewicz
02 июль 2011, в 12:09

Поделиться

Некоторые компиляторы могут не согласиться с использованием переменной ‘jj’ после завершения цикла for. Поскольку переменная объявлена ​​внутри цикла for, она уничтожается сразу после ее выполнения. Таким образом, когда вы объявляете свою переменную итерации вне цикла for, она остается там для дальнейшего использования.

В действительности это не работает так, и поэтому вы можете заставить компилятор игнорировать ошибку, добавив «-fpermissive».

Matheus Z
04 сен. 2013, в 19:31

Поделиться

False: for(...;...;...;);

True: for(...;...;...;)

Нельзя использовать точку с запятой, ;

Emre q
27 янв. 2016, в 17:31

Поделиться

Ещё вопросы

  • 1Почему просмотр списка Android иногда исчезает после вызова запроса на базовом курсоре?
  • 0Положение Увеличенное изображение при наведении
  • 1Android, я должен сделать MediaPlayer сервисом?
  • 0Предотвратить ВЫБОР одинаковых строк в параллельном процессе — MySql PHP
  • 1Как избежать масштабирования андроид веб-просмотра
  • 1Проблема с vue.js для получения данных из REST API
  • 0динамический URL для JQuery TabPanel
  • 1Показать OutputStream (System.out) в текстовой области
  • 1Обновление списка по нажатию кнопки в строке этого списка
  • 1Есть ли у Android аналогичные API, такие как ProcessEvents () или DoEvents () на других платформах?
  • 0PHP создать команду копирования, как phpmyadmin
  • 0Почему Flask возвращает <embed> файлы для загрузки вместо их отображения
  • 0Ошибка: недопустимое значение для <path> attribute d = «.. для круговой диаграммы
  • 0Openlayers 3, применение массива пространственных объектов к векторным результатам в getId () не является функцией
  • 0Временные массивы устройств CUDA
  • 1Затмение андроида устройства исчезают
  • 1Версия сборки .NET — какая разница (на основе опыта System.Web.Mvc)
  • 1Установить classpath навсегда в Linux
  • 1Несколько инструкций в инструкции возврата переключателя
  • 1Дублирующий пакет при развертывании apk в эмуляторе, ошибка INSTALL_FAILED_DUPLICATE_PACKAGE
  • 0Как получить имена полей $ _POST
  • 1Может ли скала код, скомпилированный с JDK 7, работать на JVM 8?
  • 1передать параметры из C ++ для сборки в Android
  • 0заменить все ссылки, содержащие текст «редактировать» с изображением, за исключением определенного класса
  • 1javascript вложенный массив массива объектов
  • 0Как использовать border-image для браузера IE [duplicate]
  • 0Если я хочу использовать базу данных mysql с nodejs, является ли ватерлиния промежуточным программным обеспечением?
  • 1Импортировать проблемную таблицу «hibernate_sequence» с Generation.type
  • 0Запустить курсор через вектор, проверяя его границы
  • 1скопировать данные из одной таблицы в другую таблицу в другой базе данных
  • 1как получить экземпляр запущенной активности
  • 1изменить цвет треугольников плоскости триJS
  • 0Не удается получить все изображения из базы данных MySQL
  • 0Можно ли прослушивать событие из приложения, вне этого приложения
  • 1Поместить массив в DataFrame как отдельный элемент
  • 0Выберите отдельные значения в одну результирующую запись в виде списка через запятую
  • 1просмотрите папку и получите пользовательский ввод для создания нового файла
  • 1Eclipse: ошибка при добавлении внешних файлов классов / jar в путь сборки: «XYZ не может быть разрешен для типа»
  • 0C ++: первый символ в очереди неверен
  • 1Вызывать компиляторы разных языков из sts / eclipse
  • 0Создание и печать Count в таблице SQL
  • 0Разрешить разрывы строк между соседними элементами, которые не могут иметь разрывов строк
  • 0Объединение двух наборов результатов
  • 0Почему мой фон кнопки обрезается в Firefox, а не в Google Chrome?
  • 0Невозможно связать с `libPocoFoundation` Poco C ++ Framework
  • 1Можно ли анимировать переход при изменении привязки данных элементов управления?
  • 0Соотношение сторон мобильного сайта jQuery изменилось после переноса сайта
  • 0Равные высоты div (или li) в строках с шириной и высотой жидкости (готово на 90%)
  • 0MySQL объединяет таблицы и использует две разные записи из объединенной таблицы в двух разных столбцах основной таблицы
  • 0изменить изображение с помощью JavaScript на основе результата функции

Сообщество Overcoder

Здравствуйте, опять я со своими ошибками, на сей раз на плюсах.

[Error] name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
[Note] (if you use ‘-fpermissive’ G++ will accept your code)

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

class L_Book {
private:
	string name_book, autor; int pages;
	public:
	void AddBook(string a, string b, int c) {
		name_book = a;
		autor = b;
		pages = c;
	} 
	void GetAllBooks() {
		cout << "Book Name : t" << name_book << endl << "Name Autor : t" << autor <<endl << "Pages : t" << pages << endl;
	}
} ;

void main() {
	string a, b; int c; bool soft = true; short menu, kol_books;
	L_Book book [500];
	setlocale (LC_ALL, "rus");

	//////////////STARTED
	while (soft == true) {
		system ("cls");
		cout << "t 1) Добавить книгу" << endl << "t 2) Список всех книг" <<endl;
		cin >> menu;

		if (menu == 1) {
			system ("cls");
			cout << ("Сколько книг хотите добавить? "); cin >> kol_books;
			for (int i = 0; i < kol_books; i++)
				system ("cls");

				cout << "Название книги: "; cin >> a, cout << endl;
				cout << "Имя автора: "; cin >> b; cout << endl;
				cout << "Количество страниц: "; cin >> c; cout << endl;
				book[i].AddBook ( a, b, c);
			}
			cout << "Успешно добавлено." << endl;
			Sleep (3000);

		}
         if (menu == 2) { 
         	system ("cls");
         	for (int i = 0; i < kol_books; i++) {
         		book[i].GetAllBooks();
         		Sleep(1000);
         	}
         	Sleep (3000);
         }
}

#include<stdio.h></stdio.h>
#include<limits.h></limits.h>
 
#define STRLEN 10
#define ARRSIZE 10
 
typedef struct orgt {
    char  n[STRLEN];
    char  Firm[STRLEN];
    char  Model[STRLEN];
    float price;
} orgt_t;
 
void clearbuf()
{
    if (!feof(stdin))
        while (getchar() != 'n');
}
 
int main ()
{
    orgt_t s[ARRSIZE];
    printf("You start table filing!n");
 
    int i = 0;
    for(; i < ARRSIZE; i++) {
        printf("Enter  NAME: ");
        scanf("%9s", s[i].n);
        clearbuf();
 
        printf("Enter Firm: ");
        scanf("%9s", s[i].Firm);
        clearbuf();
 
        printf("Enter Model name: ");
        scanf("%9s", s[i].Model);
        clearbuf();
 
        printf("Enter price of item: ");
        scanf("%f", &s[i].price);
        clearbuf();
 
        printf("Countine? 1 - Yes 0 - Non");
        int choice;
        scanf("%d", &choice);
        if(!choice) break;
        clearbuf();
    }
 
    printf("Table:n");
    printf("-------------------------------------n");
    printf("Names     Firm      Model     pricen");
    printf("-------------------------------------n");
 
    for(int j=0; j <= i; j++) {
        printf("%-10.9s%-10.9s%-10.9s%-10.2fn",
               s[j].n, s[j].Firm, s[j].Model, (double)s[j].price);
    }
 
    printf("-------------------------------------n");
 
    return 0;
}

Понравилась статья? Поделить с друзьями:
  • Error mysqld got signal 11
  • Error mysql shutdown unexpectedly ошибка
  • Error mysql shutdown unexpectedly xampp как исправить
  • Error mysql server pid file could not be found
  • Error mysql error number 2003