Error false was not declared in this scope

Ошибка was not declared in this scope при компиляции Arduino Решение и ответ на вопрос 2439885

SergeyKagen

3 / 4 / 2

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

Сообщений: 315

1

19.04.2019, 22:16. Показов 131657. Ответов 14

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


Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void setup() {
  
  Serial.begin(9600);
  int count = 0;
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}
 
void loop() {
 
  if( digitalRead(7) == HIGH ){ 
    
    while(1){ 
      delayMicroseconds(2); 
      count++;  
      if( digitalRead(7) == LOW ){ Serial.println(count); count = 0; break; }
      }
    }  
}

ошибка при компиляции «‘count’ was not declared in this scope», что не так?

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



0



marat_miaki

495 / 389 / 186

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

Сообщений: 1,688

19.04.2019, 23:26

2

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

Решение

C++
1
2
3
4
5
6
7
8
  int count = 0; //глобальная переменная
 
  void setup() {
   Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}



1



Lavad

0 / 0 / 0

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

Сообщений: 25

14.09.2019, 22:33

3

Доброго времени суток!
У меня то же сообщение, но на функцию :-(
Создал функцию (за пределами setup и loop), которая только принимает вызов, ничего не возвращает:

C++
1
2
3
4
5
void myDispay(byte x, byte y, char str) {
  lcd.setCursor(x, y);
  lcd.print(temp, 1);   // выводим данные, с точностью до 1 знака после запятой
  lcd.print(str);   // выводим писанину
  }

В loop() делаю вызов:

C++
1
myDisplay(0,0,"C");

При компиляции выделяется этот вызов, с сообщением:

‘myDisplay’ was not declared in this scope

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста.

P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…



0



Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

14.09.2019, 23:57

4

Цитата
Сообщение от Lavad
Посмотреть сообщение

Создал функцию (за пределами setup и loop),

Перевидите на нормальный язык.
Какие еще пределы?

В другом файле что ли?

Добавлено через 1 минуту

Цитата
Сообщение от Lavad
Посмотреть сообщение

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста

Читать учебники по С++ не пробовали?

https://metanit.com/cpp/tutorial/3.1.php
http://cppstudio.com/post/5291/

Специфика Arduino лишь отличается тем что пред объявления не всегда нужны.

Добавлено через 7 минут
Кроме того иногда потеряй скобок {} приводят к таким ошибкам.



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 00:09

5

Цитата
Сообщение от Lavad
Посмотреть сообщение

Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху

C++
1
void myDispay(byte x, byte y, char str);

а объявить уже в удобном месте



0



0 / 0 / 0

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

Сообщений: 25

15.09.2019, 00:48

6

Неделю назад ВПЕРВЫЕ включил Arduino Uno.
Задолго до этого писал программы под Windows (БейсикВизуал) и AVR (Basic, немного Assembler). Т.е. имеется некоторое представление об объявлении переменных, функций,… От Си всегда держался как можно дальше. Это первая и последняя причина «нечитания» книг по Си. За неделю экспериментов на Arduino мнение об этом пока не изменилось — легче вернуться к Ассму, чем копаться в Си.

Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них.

Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка.

Что не так на этот раз? :-(



0



Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 01:26

7

Цитата
Сообщение от Lavad
Посмотреть сообщение

В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

точку с запятой в конце поставил?



1



Lavad

0 / 0 / 0

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

Сообщений: 25

15.09.2019, 08:46

8

Вот скетч. Проще некуда.

C++
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
#include <PCD8544.h>
 
float temp = 0;
static PCD8544 lcd;   // даем имя подключенному дисплею (lcd)
static const byte Lm35Pin = 14;   // аналоговый пин (A0) Arduino, к которому подключен LM35
 
//void myDisplay() = 0;
//void myDisplay(byte, byte, char, float) = 0;
//void myDisplay(byte x, byte y, char str, float temp) = 0;
 
void myDispay(byte x, byte y, char str, float temp) {
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
void setup() {
  lcd.begin(84, 48);   // инициализируем дисплей
  analogReference(INTERNAL);   // подключаем внутренний ИОН на 1.1V
}
 
void loop() {
  float temp = analogRead(Lm35Pin) / 9.31;  // подсчитываем температуру (в Цельсиях)...
  myDisplay(0, 0, "C", temp);   // отправляем данные на экран
  delay(500);   // ждем 500 мсек
}

Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную.

Добавлено через 9 минут
Попробовал так:

C++
1
void myDisplay(byte x, byte y, char str, float temp);

Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф :-)

undefined reference to `myDisplay(unsigned char, unsigned char, char, float)

На этот раз он пожаловался на строку вызова функции.

Добавлено через 34 минуты
Когда что-то новое затягивает, забываешь о нормальном отдыхе, теряешь концентрацию…
Нашел ошибку. Чистейшая грамматика

C++
1
void myDispay(byte x,...

Dispay вместо Display

Добавлено через 8 минут
ValeryS, благодарю за попытку помощи!



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 10:36

9

Цитата
Сообщение от Lavad
Посмотреть сообщение

void myDisplay(byte, byte, char, float) = 0;

вот так не надо делать(приравнивать функцию к нулю)
так в классическом С++ объявляют чисто виртуальные функции, и класс в котором объявлена чисто виртуальная функция становится абстрактным. Означает что у функции нет реализации и в дочернем классе нужно обязательно реализовать функцию. А из абстрактного класса нельзя создать объект

Добавлено через 5 минут

Цитата
Сообщение от Lavad
Посмотреть сообщение

void myDispay(byte x, byte y, char str, float temp)

Цитата
Сообщение от Lavad
Посмотреть сообщение

myDisplay(0, 0, «C», temp);

просишь чтобы функция принимала символ char str, а передаешь строку "C"
или передавай символ

C++
1
myDisplay(0, 0, 'C', temp);

или проси передавать строку, например так

C++
1
void myDispay(byte x, byte y, char * str, float temp);



1



Avazart

Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

15.09.2019, 12:02

10

Кроме того наверное лучше так:

C++
1
2
3
4
5
6
7
8
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) 
{
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
myDisplay(lcd,0, 0, 'C', temp);

Тогда можно будет вынести ф-цию в отдельный файл/модуль.



1



locm

15.09.2019, 21:07

Не по теме:

Цитата
Сообщение от Lavad
Посмотреть сообщение

Arduino Uno.

Цитата
Сообщение от Lavad
Посмотреть сообщение

AVR (Basic, немного Assembler).

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.



0



Avazart

15.09.2019, 21:21

Не по теме:

Цитата
Сообщение от locm
Посмотреть сообщение

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.

Но лучше не надо …



0



Lavad

0 / 0 / 0

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

Сообщений: 25

16.09.2019, 12:12

13

Цитата
Сообщение от ValeryS
Посмотреть сообщение

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху
а объявить уже в удобном месте

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции. А сама функция может располагаться по скетчу в ЛЮБОМ месте (но за пределами setup, loop и любых других функций). И больше никаких специфических строк.

Цитата
Сообщение от ValeryS
Посмотреть сообщение

вот так не надо делать(приравнивать функцию к нулю)…

Методом проб и ошибок уже понял :-).

Цитата
Сообщение от ValeryS
Посмотреть сообщение

или передавай символ… 'C'

Если передаю в одинарных кавычках

более одного

символа, а функция ждет как char str, то выводятся на экран только самый правый из отправленных символов. Отправил «абв», а выводится «в».
Выкрутился, прописав в функции char str[], а символы отправляю через двойные кавычки.

Цитата
Сообщение от ValeryS
Посмотреть сообщение

или проси передавать строку, например так… char * str

Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).

Цитата
Сообщение от Avazart
Посмотреть сообщение

Кроме того наверное лучше так:

C++
1
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) {...}

Тогда можно будет вынести ф-цию в отдельный файл/модуль.

Благодарю за совет! Как-нибудь проверю…



0



Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

16.09.2019, 12:54

14

Цитата
Сообщение от Lavad
Посмотреть сообщение

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции

Нафиг выкиньте эти справочники.
Почитайте мои ссылки.



0



0 / 0 / 0

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

Сообщений: 25

16.09.2019, 13:00

15

Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
Но теория для меня — всего лишь набор понятий. Я же высказался после практической проверки. А как я понял, так оно и работает :-)



0



  1. 03-08-2009


    #1

    Taka is offline


    Registered User


    Not declared in this scope

    Hey if anyone could help me out here I would really appreciate it. I’m not sure what do to to get rid of the below errors/warnings.

    prime.cpp: In function ‘int main()’:
    prime.cpp:12: error: ‘isPrime’ was not declared in this scope
    prime.cpp: In function ‘int isPrime(int)’:
    prime.cpp:39: warning: converting to ‘int’ from ‘double’

    Code:

    #include <iostream>
    using namespace std;
    #include <math.h>
     
    #define TRUE 1;
    #define FALSE 0;
     
    int main()
    {
       int number;
     
       if (isPrime(number)) 
          cout << "n" << number << "is a prime numbern";
       else 
          cout << "n" << number << "is not a prime numbern";
     
       return 0;
    }
     
    void getNumber(int &number)
    {
       cout << "Please enter a positive number ";
       cin >> number;
       if (!cin.good())
       {
          printf("Invalid number enteredn");
          exit(1);
       }
    }
     
    int isPrime(int number)
    {
       int count, s;
     
       /* Every even number is not prime */
       if (number % 2 == 0) return TRUE;
     
       /* check every odd number up to the square root of the number */
       s = sqrt(number);
       for (count=3; count<=s; count+=2);
       {
          if (number % count == 0) return TRUE;
       }
       return FALSE;
    }


  2. 03-08-2009


    #2

    Codeplug is offline


    Registered User

    Codeplug's Avatar


    The compiler doesn’t know that «isPrime» is defined later in the file. You need to declare it before using it. Add the following before main:

    int isPrime(int);

    The compiler will then know that «isPrime» is a function taking/returning int, when it sees it.

    gg


  3. 03-08-2009


    #3

    Taka is offline


    Registered User


    I tried that but it came up with an «unexpected initialiser before int» error.


  4. 03-08-2009


    #4

    Taka is offline


    Registered User


    Sorry I know what it was I was doing wrong.

    Can anyone help me with why it is always printing out:

    Please enter a positive number 4

    -4195180is a prime number

    Updated code:

    Code:

    #include <iostream>
    using namespace std;
    #include <math.h>
    
    int isPrime(int);
    void getNumber(int);
    
    #define TRUE 1;
    #define FALSE 0;
    
    int main()
    {
       int number;
    
       getNumber(number);
    
       if (isPrime(number)) 
          cout << "n" << number << "is a prime numbern";
       else 
          cout << "n" << number << "is not a prime numbern";
    
       return 0;
    }
    
    void getNumber(int number)
    {
       cout << "Please enter a positive number ";
       cin >> number;
       if (!cin.good())
       {
          printf("Invalid number enteredn");
          exit(1);
       }
    }
    
    int isPrime(int number)
    {
       int count, s;
    
       /* Every even number is not prime */
       if (number % 2 == 0) return TRUE;
    
       /* check every odd number up to the square root of the number */
       s = sqrt(number);
       for (count=3; count<=s; count+=2);
       {
          if (number % count == 0) return TRUE;
       }
       return FALSE;
    }

    Last edited by Taka; 03-08-2009 at 09:12 PM.


  5. 03-08-2009


    #5

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    You should use pass by reference instead of pass by value, otherwise the number variable in the main function is never modified by getNumber().

    By the way, C++ has a bool type with true and false constants, so it does not make sense to use an int with TRUE and FALSE macros.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  6. 03-08-2009


    #6

    Taka is offline


    Registered User


    I’m sorry but I don’t know what you mean at all.


  7. 03-08-2009


    #7

    tabstop is offline


    and the Hat of Guessing

    tabstop's Avatar


    You had it right the first time — compare the original getNumber with your new one.

    Not only should «#define TRUE 1» never appear in C++, given that «true» already exists, it should most definitely not appear with a semicolon at the end. Since isPrime asks a true-false question, you should use a true-false datatype, specifically «bool».


  8. 03-08-2009


    #8

    Taka is offline


    Registered User


    When I left it as

    Code:

     void getNumber(int &number)

    I got a compile error:

    prime.cpp: In function ‘int isPrime(int)’:
    prime.cpp:44: warning: converting to ‘int’ from ‘double’
    Undefined first referenced
    symbol in file
    getNumber(int) /var/tmp//cc1BaH0f.o
    ld: fatal: Symbol referencing errors. No output written to a.out
    collect2: ld returned 1 exit status


  9. 03-08-2009


    #9

    tabstop is offline


    and the Hat of Guessing

    tabstop's Avatar


    Did you remember to change the prototype too? Otherwise post code.


  10. 03-08-2009


    #10

    Taka is offline


    Registered User


    Code:

    #include <iostream>
    using namespace std;
    #include <math.h>
    
    int isPrime(int);
    void getNumber(int);
    
    #define TRUE 1;
    #define FALSE 0;
    
    int main()
    {
       int number;
    
       getNumber(number);
    
       if (isPrime(number)) 
          cout << "n" << number << "is a prime numbern";
       else 
          cout << "n" << number << "is not a prime numbern";
    
       return 0;
    }
    
    void getNumber(int &number)
    {
       cout << "Please enter a positive number ";
       cin >> number;
       if (!cin.good())
       {
          printf("Invalid number enteredn");
          exit(1);
       }
    }
    
    int isPrime(int number)
    {
       int count, s;
    
       /* Every even number is not prime */
       if (number % 2 == 0) return TRUE;
    
       /* check every odd number up to the square root of the number */
       s = sqrt(number);
       for (count=3; count<=s; count+=2);
       {
          if (number % count == 0) return TRUE;
       }
       return FALSE;
    }


  11. 03-08-2009


    #11

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    Basically, this:

    Code:

    void getNumber(int);

    should be either:

    Code:

    void getNumber(int& number);

    or:
    Then you make the change in the function definition (implementation) as well.

    Now this:

    should be:

    Code:

    bool isPrime(int number);

    then you get rid of these lines:

    Code:

    #define TRUE 1;
    #define FALSE 0;

    Note that if you really did need them, those semi-colons should be removed, as mentioned by tabstop.

    So, no more TRUE or FALSE. What to do? Just use true or false.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  12. 03-08-2009


    #12

    Taka is offline


    Registered User


    So it should be like this?

    Code:

    #include <iostream>
    using namespace std;
    #include <math.h>
    
    int isPrime(int);
    void getNumber(int& number);
    
    #define TRUE 1
    #define FALSE 0
    
    int main()
    {
       int number;
    
       getNumber(number);
    
       if (isPrime(number)) 
          cout << "n" << number << "is a prime numbern";
       else 
          cout << "n" << number << "is not a prime numbern";
    
       return 0;
    }
    
    void getNumber(int& number)
    {
       cout << "Please enter a positive number ";
       cin >> number;
       if (!cin.good())
       {
          printf("Invalid number enteredn");
          exit(1);
       }
    }
    
    int isPrime(int number)
    {
       int count, s;
    
       /* Every even number is not prime */
       if (number % 2 == 0) return TRUE;
    
       /* check every odd number up to the square root of the number */
       s = sqrt(number);
       for (count=3; count<=s; count+=2);
       {
          if (number % count == 0) return TRUE;
       }
       return FALSE;
    }


  13. 03-08-2009


    #13

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    Quote Originally Posted by Taka

    So it should be like this?

    You’re not paying attention, are you? The code that you corrected should be removed. I was merely pointing out how it would be corrected if it were not to be removed.

    There is another thing that I did not spot earlier: you have a using directive (using namespace std; ) before a header inclusion. That is bad practice, although it might not matter especially since the header is a standard header. Move the using directive to after the header inclusion.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  14. 03-08-2009


    #14

    Taka is offline


    Registered User


    I’m sorry I’m trying to understand what you are saying but I am only learning C++ and I’m not really getting what you are trying to tell me.

    I’ve been told I need to leave the True/False statements in there thats why I didn’t take them out.


  15. 03-09-2009


    #15

    MarkZWEERS is offline


    Registered User


    Code:

    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    bool isPrime(int);
    int getNumber();
    
    int main()
    {
       int number = getNumber();
    
       if (isPrime(number)) 
          cout << "n" << number << "is a prime numbern";
       else 
          cout << "n" << number << "is not a prime numbern";
    
       return 0;
    }
    
    int getNumber()
    {
       int number;
       cout << "Please enter a positive number ";
       cin >> number;
       if (!cin.good())
       {
          printf("Invalid number enteredn");
          exit(1);
       }
       return number;
    }
    
    bool isPrime(int number)
    {
       int count, s;
       bool isprime = true;
    
       /* Every even number is not prime */
       // if (number % 2 == 0) return TRUE;
    
       /* check every odd number up to the square root of the number */
       s = sqrt(number);
       for (count=3; count<=s; count+=2);
       {
          if (number % count == 0)
            isprime = false;
       }
       return false;
    }

    Include «cmath» , not «math.h».

    In main(), affect ‘number’ by returning the number. This is the most logical.
    In the function ‘isPrime’ you don’t have to verify for both ‘true’ and ‘false’, just make it true unless otherwise found.
    Try not to use ‘return’ in loops or functions, but affect a local variable which you return always in the end (although here it doesn’t really matter).


Arduino programming is an open-source and simple stage that arranges the Arduino board into working with a particular goal in mind. An Arduino code is written in C++ yet with extra capacities and strategies. An Arduino is an equipment and programming stage broadly utilised in hardware.

In this article, we go through three quick fixes for the error ‘was not declared in this scope’.

Also read: How to solve the Tower of Hanoi problem using Python?


What does the error mean?

Every programming language has a concept of Scope. Scope tells us where a specific variable, constant or function is accessible and usable. It refers to the area of code a statement, block, or name. The scope of an entity determines where that entity is usable in other parts of the program. The scope of a block determines where that block can be used in other blocks, and the scope of a name determines where that name can be used in other names.

There are two types of scope in programming languages: local and global. Local scope refers to the identifiers and symbols visible inside a block of code. Global scope, on the other hand, refers to the identifiers and symbols visible outside a block of code.

The error ‘was not declared in this scope’ generally occurs when a variable or function is not accessible to its call. A global variable in Arduino is the variable that is declared outside any function, including the setup() and loop() functions. Any variable declared inside a function or loop has restrictive access and is a local variable.

If any other function calls a local variable, it gives an error. To call any variable or function in any other function, including the setup() and loop() function, it should be declared as a global variable.

Also read: How to stop an Arduino program?


There are the quick fixes for the Arduino error: was not declared in the scope.

Declare the variable

Before assigning a value to the variable, make sure to define it. There are 16 data types commonly used in Arduino coding. Each data type expresses the nature of the value assigned to it. If the data type and value doesn’t match, an error arises. Also, if a variable is assigned any value without its declaration or data type, the error occurs.

Always ensure to declare the variable before the assignment. There are two ways to do this.

How to solve Arduino error: 'was not declared in this scope'?

There are three variables in the above example – num1, num2 and num3. The variable num1 has been declared separately and assigned to a data type corresponding value in the loop. The variable num2 has been declared and assigned in the same line of code. The variable num3, on the other hand, has directly been assigned a value without its declaration. This causes the error, as shown above.


Other details

There may be errors arising even after proper declaration and assignment of the variable. This may be due to incorrect or absence of the closing brackets, semicolons or improper declaration of functions. Ensure proper use of syntax when defining loops and functions. Every opening in curly brace must be accounted for and closed. Extra closing braces also cause errors. Alongside, semicolons hold their importance. A semicolon missed can cause the entire program to go haywire.


Library folder

Many times, variables call or use functions that require importing a few specific libraries.

How to solve Arduino error: 'was not declared in this scope'?

In the example above, the variable num calls the square root function – sqrt() from the maths library of Arduino. If we call a function without including its library first, an error occurs. There are multiple inbuilt and standard libraries in Arduino, while a few special libraries must be included separately.

Also read: What is ‘does not name a type’ in Arduino: 2 Fixes.

лови:

/*
Лабораторный блок питания под управлением arduino
Версия 2 (26.02.2015)
Для дополнительной информации посетите http://start.net.ua/blog/lab_power_arduino/
*/

#include <LiquidCrystal.h>;
#include <EEPROM.h>
LiquidCrystal lcd(11, 6, 5, 4, 3, 2); //rs, e, d4, d5, d6, d7

// задаем константы

float umax = 17.00; //максимальное напряжение
float umin = 0.00; //минимальное напряжение
float ah = 0.0000; //Cчетчик Ампер*часов
const int down = 10; //выход валкодера 1/2
const int up = 8; //выход валкодера 2/2
const int pwm = 9; //выход ШИМ
const int power = 7; //управление релюхой
long previousMillis = 0; //храним время последнего обновления дисплея
long maxpwm = 0; //циклы поддержки максимального ШИМ
long interval = 500; // интервал обновления информации на дисплее, мс
int mig = 0; //Для енкодера (0 стоим 1 плюс 2 минус)
float level = 0; //»уровень» ШИМ сигнала
float com = 100;
long com2 = 0;
int mode = 0;//режим (0 обычный, спабилизация тока, защита по току)
int mode1 = 0;
float Ioutmax = 1.0; //заданный ток
int set = 0; //пункты меню, отображение защиты…
int knopka_a = 0; //состояние кнопок
int knopka_b = 0;
int knopka_ab = 0;
boolean off = false;
boolean red = false;
boolean blue = false;
float counter = 5; // переменная хранит заданное напряжение
int disp = 0; //режим отображения 0 ничего, 1 мощьность, 2 режим, 3 установленный ток, 4 шим уровень
float Uout ; //напряжение на выходе

const int Pin=A2; // номер выхода, подключенного к реле
int PinState = LOW; // этой переменной устанавливаем состояние реле
long previousMillis1 = 0; // храним время последнего переключения реле
long interval1 = 1000; // интервал между включение/выключением реле (1 секунда)
long interval2 = 500;

int incomingByte;

void EEPROM_float_write(int addr, float val) // запись в ЕЕПРОМ
{
byte *x = (byte *)&val;
for(byte i = 0; i < 4; i++) EEPROM.write(i+addr, x[i]);
}

float EEPROM_float_read(int addr) // чтение из ЕЕПРОМ
{
byte x[4];
for(byte i = 0; i < 4; i++) x[i] = EEPROM.read(i+addr);
float *y = (float *)&x;
return y[0];
}

void setup() {
cli();
DDRB |= 1<<1 | 1<<2;
PORTB &= ~(1<<1 | 1<<2);
TCCR1A = 0b00000010;
//TCCR1A = 0b10100010;
TCCR1B = 0b00011001;
ICR1H = 255;
ICR1L = 255;
sei();
int pwm_rez = 13;
pwm_rez = pow(2, pwm_rez);
ICR1H = highByte(pwm_rez);
ICR1L = lowByte(pwm_rez);

// задаем режим выхода для порта, подключенного к реле
pinMode(Pin, OUTPUT);

Serial.begin(9600);

pinMode(pwm, OUTPUT);
pinMode(down, INPUT);
pinMode(up, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(power, OUTPUT);
pinMode(A4, OUTPUT);
pinMode(A5, OUTPUT);
// поддерживаем еденицу на входах от валкодера
digitalWrite(up, 1);
digitalWrite(down, 1);
//поддерживаем еденицу на контактах кнопок
digitalWrite(12, 1);
digitalWrite(13, 1);
//запуск дисплея
lcd.begin(16, 2);
lcd.print(» WELCOME! «);

//загружаем настройки из памяти МК
counter = EEPROM_float_read(0);
Ioutmax = EEPROM_float_read(4);
mode = EEPROM_float_read(12);
disp = EEPROM_float_read(10);
//Если в памяти еще нет настроек — задаем что нибудь кроме нулей
if(counter==0) counter = 5; //5 вольт
if(Ioutmax==0) Ioutmax = 2; //2 ампера

//включаем реле
digitalWrite(power, 1);
}

//функции при вращении енкодера
void uup(){ //енкодер +
if(set==0){//обычный режим — добавляем напряжения
if(counter<umax) {
counter = counter+0.1;//добавляем
}
}
if(set==1){ //переключаем режим работы вперед
mode = mode+1;
if(mode>2) mode=2;
}

if(set==2){ //переключаем режим работы вперед (ON)
mode1 = mode1+1;
if(mode1>1) mode1=1;
}
if(set==3){ //настройка тока, добавляем ток
iplus();
}

if(set==4){//сброс счетчика А*ч
ah = 0;
set = 0;
disp = 5;
}

if(set==5){//сохранение текущих настроек в память
save();
}
}

void udn(){ //валкодер —
if(set==0){
if(counter>umin+0.1)counter = counter-0.1; //убавляем напнряжение
}
if(set==1){
mode = mode-1; //переключаем режим работы назад
if(mode<0) mode=0;
}
if(set==2){ //переключаем режим работы назад (OFF)
mode1 = mode1-1;
if(mode1<0) mode1=0;
}
if(set==3){//убавляем ток
iminus();
}
}

void iplus(){
Ioutmax = Ioutmax+0.01;
if(Ioutmax>0.2) Ioutmax=Ioutmax+0.04;
if(Ioutmax>1) Ioutmax=Ioutmax+0.05;

if(Ioutmax>8.00) Ioutmax=8.00;
}

void iminus(){
Ioutmax = Ioutmax-0.01;
if(Ioutmax>0.2) Ioutmax=Ioutmax-0.04;
if(Ioutmax>1) Ioutmax=Ioutmax-0.05;

if(Ioutmax<0.03) Ioutmax=0.03;
}

void save(){
lcd.clear();
lcd.setCursor (0, 0);
lcd.print(» S A V E — OK «);

EEPROM_float_write(0, counter);
EEPROM_float_write(4, Ioutmax);
EEPROM_float_write(12, mode);
EEPROM_float_write(10, disp);
//мигаем светодиодами
digitalWrite(A4, 1);
digitalWrite(A5, 1);
delay(500);
digitalWrite(A4, 0);
digitalWrite(A5, 0);
set = 0; //выходим из меню
}

void loop() //основной цикл работы МК
{

// здесь будет код, который будет работать постоянно
// и который не должен останавливаться на время между переключениями свето
unsigned long currentMillis1 = millis();

//проверяем не прошел ли нужный интервал, если прошел то
if((currentMillis1 — previousMillis1 > interval1)&(mode1==1)) {
// сохраняем время последнего переключения
previousMillis1 = currentMillis1;

// если светодиод не горит, то зажигаем, и наоборот

if (PinState == LOW)
PinState = HIGH;

else
PinState = LOW;

// устанавливаем состояния выхода, чтобы включить или выключить светодиод
digitalWrite(Pin, PinState);
}

unsigned long currentMillis = millis();

/* Вншнее управление */
if (Serial.available() > 0) { //если есть доступные данные
// считываем байт
incomingByte = Serial.read();

}else{
incomingByte = 0;
}

if(incomingByte==97){ //a
if(counter>umin+0.1)counter = counter-0.1; //убавляем напнряжение

}
if(incomingByte==98){ //b

if(counter<umax) counter = counter+0.1;//добавляем

}

if(incomingByte==99){ //c
iminus();
}

if(incomingByte==100){ //d
iplus();
}

if(incomingByte==101) mode = 0;
if(incomingByte==102) mode = 1;
if(incomingByte==103) mode = 2;
if(incomingByte==104) mode1 = 1;
if(incomingByte==105) save();
if(incomingByte==106){
digitalWrite(power, 1); //врубаем реле если оно было выключено
delay(100);
digitalWrite(A4, 0); //гасим красный светодиод
Serial.print(‘t’);
Serial.print(0);
Serial.print(‘;’);
off = false;
set = 0;//выходим из меню
}

if(incomingByte==107) off = true;
if(incomingByte==108) ah = 0;

/* конец внешнего управления */

//получаем значение напряжения и тока в нагрузке
//float Ucorr = 0.00; //коррекция напряжения, при желании можно подстроить
//float Uout = analogRead(A1) * ((5.0 + Ucorr) / 1023.0) * 5.0; //узнаем напряжение на выходе
float Uout = analogRead(A1) * (5.0 / 1023.0) * 5.0; //узнаем напряжение на выходе

float Iout = analogRead(A0) / 100.00; // узнаем ток в нагрузке

//if(Iout==0.01) Iout = 0.03; else
//if(Iout==0.02) Iout = 0.04; else
//if(Iout==0.03) Iout = 0.05; else
//if(Iout==0.04) Iout = 0.06; else
//if(Iout>=0.05) Iout = Iout + 0.02;
//if(Iout>=0.25)Iout = Iout + 0.01;
//if(Iout>=1)Iout = Iout * 1.02;

/* ЗАЩИТА и выключение */

if (((Iout>(counter+0.3)*2.0) | Iout>10.0 | off) & set<4 & millis()>100 ) // условия защиты

{
digitalWrite(power, 0); //вырубаем реле
level = 0; //убираем ШИМ сигнал
digitalWrite(A4, 1);

Serial.print(‘I0;U0;r1;W0;’);
Serial.println(‘ ‘);
set = 6;

}

//Зашита от длительного максимального шим
if (level==8190 & off==false)
{
if(set<4)//если уже не сработала защита
{
maxpwm++; //добавляем +1 к счетчику
digitalWrite(A4, 1); //светим красным для предупреждения о максимальном ШИМ
}
}
else //шим у нас не максимальный, поэтому поубавим счетчик
{
maxpwm—;
if(maxpwm<0)//если счетчик дошел до нуля
{
maxpwm = 0; //таким его и держим
if(set<4) digitalWrite(A4, 0); // гасим красный светодиод. Перегрузки нет.
}
}

/* ЗАЩИТА КОНЕЦ */

// считываем значения с входа валкодера
boolean regup = digitalRead(up);
boolean regdown = digitalRead(down);

if(regup<regdown) mig = 1; // крутится в сторону увеличения
if(regup>regdown) mig = 2; // крутится в сторону уменшения
if(!regup & !regdown) //момент для переключения
{
if(mig==1) uup();//+
if(mig==2) udn(); //-
mig = 0; //сбрасываем указатель направления
}

if(mode==0 | mode==1) //если управляем только напряжением (не режим стабилизации тока)
{

//Сравниваем напряжение на выходе с установленным, и принимаем меры..
if(Uout>counter)
{
float raz = Uout — counter; //на сколько напряжение на выходе больше установленного…
if(raz>0.05)
{
level = level — raz * 20; //разница большая управляем грубо и быстро!
}else{
if(raz>0.015) level = level — raz * 3 ; //разница небольшая управляем точно
}
}
if(Uout<counter)
{
float raz = counter — Uout; //на сколько напряжение меньше чем мы хотим
if(raz>0.05)
{
level = level + raz * 20; //грубо
}else{
if(raz>0.015) level = level + raz * 3 ; //точно
}
}

if(mode==1&&Iout>Ioutmax) //режим защиты по току, и он больше чем мы установили
{
digitalWrite(power, 0); //вырубаем реле
Serial.print(‘t’);
Serial.print(2);
Serial.print(‘;’);

//зажигаем красный светодиод
digitalWrite(A4, 1);
level = 0; //убираем ШИМ сигнал
set=5; //режим ухода в защиту…
}

}else{ //режим стабилизации тока

if(Iout>=Ioutmax)
{
//узнаем запас разницу между током в нагрузке и установленным током
float raz = (Iout — Ioutmax);
if(raz>0.3) //очень сильно превышено (ток больше заданного более чем на 0,3А)
{
level = level — raz * 20; //резко понижаем ШИМ
}else{
if(raz>0.05) //сильно превышено (ток больше заданного более чем на 0,1А)
{
level = level — raz * 5; //понижаем ШИМ
}else{
if(raz>0.00) level = level — raz * 2; //немного превышен (0.1 — 0.01А) понижаем плавно
}
}

//зажигаем синий светодиод
digitalWrite(A5, 1);
}else{ //режим стабилизации тока, но ток у нас в пределах нормы, а значит занимаемся регулировкой напряжения
digitalWrite(A5, 0);//синий светодиод не светится

//Сравниваем напряжение на выходе с установленным, и принимаем меры..
if(Uout>counter)
{
float raz = Uout — counter; //на сколько напряжение на выходе больше установленного…
if(raz>0.1)
{
level = level — raz * 20; //разница большая управляем грубо и быстро!
}else{
if(raz>0.015) level = level — raz * 5; //разница небольшая управляем точно
}
}
if(Uout<counter)
{
float raz = counter — Uout; //на сколько напряжение меньше чем мы хотим
float iraz = (Ioutmax — Iout); //
if(raz>0.1 & iraz>0.1)
{
level = level + raz * 20; //грубо
}else{
if(raz>0.015) level = level + raz ; //точно
}
}
}
}//конец режима стабилизации тока

if(off) level = 0;
if(level<0) level = 0; //не опускаем ШИМ ниже нуля
if(level>8190) level = 8190; //не поднимаем ШИМ выше 13 бит
//Все проверили, прощитали и собственно отдаем команду для силового транзистора.
if(ceil(level)!=255) analogWrite(pwm, ceil(level)); //подаем нужный сигнал на ШИМ выход (кроме 255, так как там какая-то лажа)

/* УПРАВЛЕНИЕ */

if (digitalRead(13)==0 && digitalRead(12)==0 && knopka_ab==0 ) { // нажата ли кнопка a и б вместе
knopka_ab = 1;

//ah = 0.000;

knopka_ab = 0;
}

if (digitalRead(13)==0 && knopka_a==0) { // нажата ли кнопка А (disp)
knopka_a = 1;
disp = disp + 1; //поочередно переключаем режим отображения информации
if(disp==6) disp = 0; //дошли до конца, начинаем снова
}

if (digitalRead(12)==0 && knopka_b==0) { // нажата ли кнопка Б (menu)
knopka_b = 1;
set = set+1; //
if(set>5 | off) {//Задействован один из режимов защиты, а этой кнопкой мы его вырубаем. (или мы просто дошли до конца меню) //количество меню
off = false;
digitalWrite(power, 1); //врубаем реле если оно было выключено
delay(100);
digitalWrite(A4, 0); //гасим красный светодиод
Serial.print(‘t’);
Serial.print(0);
Serial.print(‘;’);
Serial.print(‘r’);
Serial.print(0);
Serial.print(‘;’);
Serial.println(‘ ‘);
set = 0;//выходим из меню
}
lcd.clear();//чистим дисплей
}

//сбрасываем значения кнопок или чего-то вроде того.
if(digitalRead(12)==1&&knopka_b==1) knopka_b = 0;
if(digitalRead(13)==1&&knopka_a==1) knopka_a = 0;

/* COM PORT */

if(currentMillis — com2 > com) {
// сохраняем время последнего обновления
com2 = currentMillis;

//Считаем Ампер*часы
ah = ah + (Iout / 36000);

Serial.print(‘U’);
Serial.print(Uout);
Serial.print(‘;’);

Serial.print(‘I’);
Serial.print(Iout);
Serial.print(‘;’);

Serial.print(‘i’);
Serial.print(Ioutmax);
Serial.print(‘;’);

Serial.print(‘u’);
Serial.print(counter);
Serial.print(‘;’);

Serial.print(‘W’);
Serial.print(level);
Serial.print(‘;’);

Serial.print(‘c’);
Serial.print(ah);
Serial.print(‘;’);

Serial.print(‘m’);
Serial.print(mode);
Serial.print(‘;’);

Serial.print(‘r’);
Serial.print(digitalRead(A4));
Serial.print(‘;’);

Serial.print(‘b’);
Serial.print(digitalRead(A5));
Serial.print(‘;’);

Serial.println(‘ ‘);

}

/* ИНДИКАЦИЯ LCD */

if(set==0){
//стандартный екран

//выводим уснановленное напряжение на дисплей
lcd.setCursor (0, 1);
lcd.print(«U>»);
if(counter<10) lcd.print(» «); //добавляем пробел, если нужно, чтобы не портить картинку
lcd.print (counter,1); //выводим установленное значение напряжения
lcd.print («V «); //пишем что это вольты

//обновление информации

/*проверяем не прошел ли нужный интервал, если прошел то
выводим реальные значения на дисплей*/

if(currentMillis — previousMillis > interval) {
// сохраняем время последнего обновления
previousMillis = currentMillis;
//выводим актуальные значения напряжения и тока на дисплей

lcd.setCursor (0, 0);
lcd.print(«U=»);
if(Uout<9.99) lcd.print(» «);
lcd.print(Uout,2);
lcd.print(«V I=»);
lcd.print(Iout, 2);
lcd.print(«A «);

//дополнительная информация
lcd.setCursor (8, 1);
if(disp==0){ //ничего
lcd.print(» «);
}
if(disp==1){ //мощьность
lcd.print(» «);
lcd.print (Uout * Iout,2);
lcd.print(«W «);
}
if(disp==2){ //режим БП
if(mode==0)lcd.print («standart»);
if(mode==1)lcd.print («shutdown»);
if(mode==2)lcd.print (» drop»);
}
if(disp==3){ //режим БП
if(mode1==0) lcd.print(«Off»);
if(mode1==1) lcd.print(«On «);
}
if(disp==4){ //максимальный ток
lcd.print (» I>»);
lcd.print (Ioutmax, 2);
lcd.print («A «);
}
if(disp==5){ // значение ШИМ
lcd.print («pwm:»);
lcd.print (ceil(level), 0);
lcd.print (» «);
}
if(disp==6){ // значение ШИМ
if(ah<1){
//if(ah<0.001) lcd.print (» «);
if(ah<=0.01) lcd.print (» «);
if(ah<=0.1) lcd.print (» «);
lcd.print (ah*1000, 1);
lcd.print («mAh «);
}else{
if(ah<=10) lcd.print (» «);
lcd.print (ah, 3);
lcd.print («Ah «);
}
}
}
}

/* ИНДИКАЦИЯ МЕНЮ */
if(set==1)//выбор режима
{
lcd.setCursor (0, 0);
lcd.print(«> MENU 1/5 «);
lcd.setCursor (0, 1);
lcd.print(«mode: «);
//режим (0 обычный, спабилизация тока, защита по току)
if(mode==0) lcd.print(«normal «);
if(mode==1) lcd.print(«shutdown «);
if(mode==2) lcd.print(«drop «);
}

if(set==2){//настройка сульфатации
lcd.setCursor (0, 0);
lcd.print(«> MENU 2/5 «);
lcd.setCursor (0, 1);
lcd.print(«DeSulfat: «);
if(mode1==0) lcd.print(«Off»);
if(mode1==1) lcd.print(«On «);

}
if(set==3){//настройка тока
lcd.setCursor (0, 0);
lcd.print(«> MENU 3/5 «);
lcd.setCursor (0, 1);
lcd.print(«I out max: «);
lcd.print(Ioutmax);
lcd.print(«A»);
}
if(set==4){//спрашиваем хочет ли юзер сохранить настройки
lcd.setCursor (0, 0);
lcd.print(«> MENU 4/5 «);
lcd.setCursor (0, 1);
lcd.print(«Reset A*h? ->»);
}

if(set==5){//спрашиваем хочет ли юзер сохранить настройки
lcd.setCursor (0, 0);
lcd.print(«> MENU 5/5 «);
lcd.setCursor (0, 1);
lcd.print(«Save options? ->»);
}
/* ИНДИКАЦИЯ ЗАЩИТЫ */
if(set==6){//защита. вывод инфы
lcd.setCursor (0, 0);
lcd.print(«ShutDown! «);
lcd.setCursor (0, 1);
lcd.print(«Iout»);
lcd.print(«>Imax(«);
lcd.print(Ioutmax);
lcd.print(«A)»);
level=0;
Serial.print(‘I0;U0;r1;W0;’);
Serial.println(‘ ‘);
}

if(set==7){//защита. вывод инфы критическое падение напряжения
Serial.print(‘I0;U0;r1;W0;’);
digitalWrite(A4, true);
Serial.println(‘ ‘);
level=0;
lcd.setCursor (0, 0);
if (off==false){ lcd.print(«[ OVERLOAD ]»);
lcd.setCursor (0, 1);
//и обьясняем юзеру что случилось

if((Iout>(counter+0.3)*2.0) | Iout>10.0){
Serial.print(‘t’);
Serial.print(1);
Serial.print(‘;’);
lcd.print(» Iout >= Imax «);
}

}else{

lcd.print(«[ OFF ]»);
lcd.setCursor (0, 1);
Serial.print(‘t’);
Serial.print(4);
Serial.print(‘;’);
}
}

}

  • Forum
  • Beginners
  • «___ was not declared in this scope» err

«___ was not declared in this scope» errors

I am receiving compiler errors as follows and do not know how to fix this. I know it’s the same type of error, I just don’t exactly know how to fix this error. Thanks in advanced!

main.cpp: In function ‘int main()’:
main.cpp:26:18: error: ‘count’ was not declared in this scope
for (count = 1; count <= 12; count ++);
^
main.cpp:28:13: error: ‘count’ was not declared in this scope
count = count + 1;
^
main.cpp:29:13: error: ‘output’ was not declared in this scope
output count;
^

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
#include <iostream>
#include <cstdlib>
#include <string>
    using namespace std;
    int main()
    {
            int acctNum;
            string firstName;
            string lastName;
            int purchasePrice;
            int payment;
           
            
            cout << "Please enter account number";
            cin >> acctNum;
            cout << "Please enter customer's first name";
            cin >> firstName;
            cout << "Please enter purchase price";
            cin >> purchasePrice;
            
            payment = purchasePrice / 12;
            cout << "Customer first name:" << firstName <<endl;
            cout << "Customer last name:" << lastName <<endl;
            cout << "Account number:" << acctNum <<endl;
            
            for (count = 1; count <= 12; count ++);
            cout << "Payment number";
            count = count + 1;
            output count;
    }

Last edited on

You’re getting that error because you hadn’t initialized the ‘count’ variable. Write
int count; after int payment;

Also replace output count with cout<<count;
cout is used for console output. There’s nothing called output in STL of C++

Also:
can you explain what you’re trying to do with this block:

1
2
3
4
            for (count = 1; count <= 12; count ++);
            cout << "Payment number";
            count = count + 1;
            output count;

Last edited on

Hello bkatic,

In addition to what Nwb has said you should give this a read http://www.cplusplus.com/doc/tutorial/control/#for

After yo will notice that for loops are generally written as:

1
2
3
4
for (int count = 1; count <= 12; count++)
{
    // <--- your code here.
}

The «int» allows you to define the variable count for use as a local variable in the for loop.

To what you think is in the for loop. Actually nothing because of the semicolon at the end of line 27 that should not be there. What it does is limit the for loop to just that line.

This is what your code looks line in a different way:

1
2
3
4
5
6
7
for (count = 1; count <= 12; count++);

cout << "Payment number";
	
count = count + 1;
	
output count;

I think this is what you intended:

1
2
3
4
5
6
7
8
for (int count = 1; count <= 12; count++)
{
	cout << "Payment number";

	count = count + 1;

	output count;
}

What is the point of line 5 in the above code? Between this and the for loop you are adding 2 to count on each iteration of the loop. Adding to count is what the third part of the for condition is for.

Hope that helps,

Andy

Wow, thank you for the responses! I finally got it to work. As to what I’m trying to do with the

1
2
3
4
for (count = 1; count <=12; count ++)
cout << "Payment number";
count = count + 1;
cout << count; 

is from the pseudocode my homework assignment gave me. The pseudocode is as follows:

for count 1 to 12
output «Payment Number», count, «: $» , payment.
endfor

For context the assignment is designing an application that accept’s a client’s loan amount and monthly payment amount and outputs the loan balance each month until the loan is paid off.

But after further inspection and your feedback I understand why it doesn’t make sense and I have to switch things around. Thank you again!

So you’re supposed to display
"Payment Number" count ": $" payment
for 12 purchases

( In your for loop you need to add braces like Andy said, but also you don’t need count = count + 1 because count++ in the for parameter does that job for you. You must have been confused with while )

But where will you get the ‘payment’ from? Something is missing because the program accepts only 1 purchase but is asked to display 12 purchases??

Also I didn’t get why «payment = purchasePrice / 12;» is being done.
And I suspect that purchasePrice is supposed to be an array. Also lastName was never assigned, you can’t call it when it’s not assigned.

Topic archived. No new replies allowed.

Example

This error happens if a unknown object is used.

Variables

Not compiling:

#include <iostream>

int main(int argc, char *argv[])
{
    {
        int i = 2;
    }

    std::cout << i << std::endl; // i is not in the scope of the main function

    return 0;
}

Fix:

#include <iostream>

int main(int argc, char *argv[])
{
    {
        int i = 2;
        std::cout << i << std::endl;
    }

    return 0;
}

Functions

Most of the time this error occurs if the needed header is not
included (e.g. using std::cout without #include <iostream>)

Not compiling:

#include <iostream>

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

void doCompile()
{
    std::cout << "No!" << std::endl;
}

Fix:

#include <iostream>

void doCompile(); // forward declare the function

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

void doCompile()
{
    std::cout << "No!" << std::endl;
}

Or:

#include <iostream>

void doCompile() // define the function before using it
{
    std::cout << "No!" << std::endl;
}

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

Note: The compiler interprets the code from top to bottom (simplification). Everything must be at least declared (or defined) before usage.

Tips: If you need C++ homework help from experts, you can always rely upon assignment helpers.

Понравилась статья? Поделить с друзьями:
  • Error false python
  • Error failure writing sector 0xf8000 to hd0
  • Error failure to obtain a verilog simulation license
  • Error failure reading sector 0x802 from hd0 entering rescue mode
  • Error failure processing png image