Введение
При использовании новой версии компилятора языка MQL4 некоторые старые программы могут выдавать ошибки.
В старой версии компилятора во избежание критического завершения программ многие ошибки обрабатывались средой исполнения и не приводили к остановке работы. Например, деление на ноль или выход за пределы массива являются критическими ошибками и обычно приводят к аварийному завершению. Проявляются такие ошибки лишь в некоторых состояниях при определенных значениях переменных, однако о таких ситуациях следует знать и корректно их обрабатывать.
Новый компилятор позволяет обнаружить реальные или потенциальные источники ошибок и повысить качество кода.
В этой статье мы рассмотрим возможные ошибки, возникающие при компиляции старых программ, и методы их устранения.
- Ошибки компиляции
- 1.1. Идентификатор совпадает с зарезервированным словом
- 1.2. Специальные символы в наименованиях переменных и функций
- 1.3. Ошибки использования оператора switch
- 1.4. Возвращаемые значения у функций
- 1.5. Массивы в аргументах функций
- Ошибки времени выполнения
- 2.1. Выход за пределы массива (Array out of range)
- 2.2. Деление на ноль (Zero divide)
- 2.3. Использование 0 вместо NULL для текущего символа
- 2.4. Строки в формате Unicodе и их использование в DLL
- 2.5. Совместное использование файлов
- 2.6. Особенность преобразования datetime
- Предупреждения компилятора
- 3.1. Пересечения имен глобальных и локальных переменных
- 3.2. Несоответствие типов
- 3.3. Неиспользуемые переменные
1. Ошибки компиляции
При наличии ошибок в коде программа не может быть скомпилирована.
Для полного контроля всех ошибок рекомендуется использовать строгий режим компиляции, который устанавливается директивой:
#property strict
Этот режим значительно упрощает поиск ошибок.
1.1. Идентификатор совпадает с зарезервированным словом
Если наименование переменной или функции совпадает с одним из зарезервированных слов:
int char[]; int char1[]; int char() { return(0); }
то компилятор выводит сообщения об ошибках:
Рис.1. Ошибки «unexpected token» и «name expected»
Для исправления данной ошибки нужно исправить имя переменной или функции.
1.2. Специальные символы в наименованиях переменных и функций
Если наименования переменных или функций содержат специальные символы ($, @, точка):
int $var1; int @var2; int var.3; void f@() { return; }
то компилятор выводит сообщения об ошибках:
Рис.2. Ошибки «unknown symbol» и «semicolon expected»
Для исправления данной ошибки нужно скорректировать имена переменных или функций.
1.3. Ошибки использования оператора switch
Старая версия компилятора позволяла использовать любые значения в выражениях и константах оператора switch:
void start() { double n=3.14; switch(n) { case 3.14: Print("Pi");break; case 2.7: Print("E");break; } }
В новом компиляторе выражения и константы оператора switch должны быть целыми числами, поэтому при использовании подобных конструкций возникают ошибки:
Рис.3. Ошибки «illegal switch expression type» и «constant expression is not integral»
В таких случаях можно использовать явные сравнения численных значений, например:
void start() { double n=3.14; if(n==3.14) Print("Pi"); else if(n==2.7) Print("E"); }
1.4. Возвращаемые значений функций
Все функции, кроме void, должны возвращать значение объявленного типа. Например:
int function()
{
}
При строгом режиме компиляции (strict) возникает ошибка:
Рис.4. Ошибка «not all control paths return a value»
В режиме компиляции по умолчанию компилятор выводит предупреждение:
Рис.5. Предупреждение «not all control paths return a value»
Если возвращаемое значение функции не соответствует объявлению:
int init() { return; }
то при строгом режиме компиляции возникает ошибка:
Рис.6. Ошибка «function must return a value»
В режиме компиляции по умолчанию компилятор выводит предупреждение:
Рис.7. Предупреждение ‘return — function must return a value»
Для исправления таких ошибок в код функции нужно добавить оператор возврата return c возвращаемым значением соответствующего типа.
1.5. Массивы в аргументах функций
Массивы в аргументах функций теперь передаются только по ссылке.
double ArrayAverage(double a[]) { return(0); }
Данный код при строгом режиме компиляции (strict) приведет к ошибке:
Рис.8. Ошибка компилятора «arrays passed by reference only»
В режиме компиляции по умолчанию компилятор выводит предупреждение:
Рис.9. Предупреждение компилятора «arrays passed by reference only»
Для исправления таких ошибок нужно явно указать передачу массива по ссылке, добавив префикс & перед именем массива:
double ArrayAverage(double &a[]) { return(0); }
Следует отметить, что теперь константные массивы (Time[], Open[], High[], Low[], Close[], Volume[]) не могут быть переданы по ссылке. Например, вызов:
ArrayAverage(Open);
вне зависимости от режима компиляции приводит к ошибке:
Рис.10. Ошибка ‘Open’ — constant variable cannot be passed as reference
Для устранения подобных ошибок нужно скопировать необходимые данные из константного массива:
double OpenPrices[]; ArrayCopy(OpenPrices,Open,0,0,WHOLE_ARRAY); ArrayAverage(OpenPrices);
2. Ошибки времени выполнения
Ошибки, возникающие в процессе исполнения кода программы принято называть ошибками времени выполнения (runtime errors). Такие ошибки обычно зависят от состояния программы и связаны с некорректными значениями переменных.
Например, если переменная используется в качестве индекса элементов массива, то ее отрицательные значения неизбежно приведут к выходу за пределы массива.
2.1. Выход за пределы массива (Array out of range)
Эта ошибка часто возникает в индикаторах при обращении к индикаторным буферам. Функция IndicatorCounted() возвращает количество баров, неизменившихся после последнего вызова индикатора. Значения индикаторов на уже рассчитанных ранее
барах не нуждаются в пересчете, поэтому для ускорения расчетов
достаточно обрабатывать только несколько последних баров.
Большинство индикаторов, в которых используется данный способ оптимизации вычислений, имеют вид:
int start() { if (Bars<100) return(-1); int counted_bars=IndicatorCounted(); if(counted_bars<0) return(-1); int limit=Bars-counted_bars; if(counted_bars==0) { limit--; limit-=10; } else { limit++; } for (int i=limit; i>0; i--) { Buff1[i]=0.5*(Open[i+5]+Close[i+10]) } }
Часто встречается некорректная обработка случая counted_bars==0 (начальную позицию limit нужно уменьшить на значение, равное 1 + максимальный индекс относительно переменной цикла).
Также следует помнить о том, что в момент исполнения функции start() мы можем обращаться к элементам массивов индикаторных буферов от 0 до Bars()-1. Если есть необходимость работы с массивами, которые не являются индикаторными буферами, то их размер следует увеличить при помощи функции ArrayResize() в соответствии с текущим размером индикаторных буферов. Максимальный индекс элемента для адресации также можно получить вызовом ArraySize() с одним из индикаторных буферов в качестве аргумента.
2.2. Деление на ноль (Zero divide)
Ошибка «Zero divide» возникает в случае, если при выполнении операции деления делитель оказывается равен нулю:
void OnStart() { int a=0, b=0,c; c=a/b; Print("c=",c); }
При выполнении данного скрипта во вкладке «Эксперты» возникает сообщение об ошибке и завершении работы программы:
Рис.11. Сообщение об ошибке «zero divide»
Обычно такая ошибка возникает в случаях, когда значение делителя определяется значениями каких-либо внешних данных. Например, если анализируются параметры торговли, то величина задействованной маржи оказывается равна 0 если нет открытых ордеров. Другой пример: если анализируемые данные считываются из файла, то в случае его отсутствия нельзя гарантировать корректную работу. По этой причине желательно стараться учитывать подобные случаи и корректно их обрабатывать.
Самый простой способ — проверять делитель перед операцией деления и выводить сообщение об некорректном значении параметра:
void OnStart() { int a=0, b=0,c; if(b!=0) {c=a/b; Print(c);} else {Print("Error: b=0"); return; }; }
В результате критической ошибки не возникает, но выводится сообщение о некорректном значении параметра и работа завершается:
Рис. 12. Сообщение о некорректном значении делителя
2.3. Использование 0 вместо NULL для текущего символа
В старой версии компилятора допускалось использование 0 (нуля) в качестве аргумента в функциях, требующих указания финансового инструмента.
Например, значение технического индикатора Moving Average для текущего символа можно было запрашивать следующим образом:
AlligatorJawsBuffer[i]=iMA(0,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);
В новом компиляторе для указания текущего символа нужно явно указывать NULL:
AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);
Кроме того, текущий символ и период графика можно указать при помощи функций Symbol() и Period().
AlligatorJawsBuffer[i]=iMA(Symbol(),Period(),13,8,MODE_SMMA,PRICE_MEDIAN,i);
2.4. Строки в формате Unicodе и их использование в DLL
Строки теперь представляют собой последовательность символов Unicode.
Следует учитывать этот факт и использовать соответствующие функции Windows. Например, при использовании функций библиотеки wininet.dll вместо InternetOpenA() и InternetOpenUrlA() следует вызывать InternetOpenW() и InternetOpenUrlW().
В MQL4 изменилась внутренняя структура строк (теперь она занимает 12 байт), поэтому при передаче строк в DLL следует использовать структуру MqlString:
#pragma pack(push,1) struct MqlString { int size; LPWSTR buffer; int reserved; }; #pragma pack(pop,1)
2.5. Совместное использование файлов
В новом MQL4 при открытии файлов необходимо явно указывать флаги FILE_SHARE_WRITE и FILE_SHARE_READ для совместного использования.
В случае их отсутствия файл будет открыт в монопольном режиме, что не позволит больше никому его открывать, пока он не будет закрыт монополистом.
Например, при работе с оффлайновыми графиками требуется явно указывать флаги совместного доступа:
ExtHandle=FileOpenHistory(c_symbol+i_period+".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ);
Подробности можно найти в статье в статье «Оффлайновые графики и новый MQL4«.
2.6. Особенность преобразования datetime
Следует иметь ввиду, что преобразование типа datetime в строку теперь зависит от режима компиляции:
datetime date=D'2014.03.05 15:46:58'; string str="mydate="+date;
Например, попытка работы с файлами, имя которых содержит двоеточие, приведет к ошибке.
3. Предупреждения компилятора
Предупреждения компилятора носят информационный характер и не являются сообщениями об ошибках, однако они указывают на возможные источники ошибок и лучше их скорректировать.
Чистый код не должен содержать предупреждений.
3.1. Пересечения имен глобальных и локальных переменных
Если на глобальном и локальном уровнях присутствуют переменные с одинаковыми именами:
int i; void OnStart() { int i=0,j=0; for (i=0; i<5; i++) {j+=i;} PrintFormat("i=%d, j=%d",i,j); }
то компилятор выводит предупреждение и укажет номер строки, на которой объявлена глобальная переменная:
Рис.13. Предупреждение «declaration of ‘%’ hides global declaration at line %»
Для исправления таких предупреждений нужно скорректировать имена глобальных переменных.
3.2. Несоответствие типов
В новой версии компилятора введена операция приведения типов.
#property strict void OnStart() { double a=7; float b=a; int c=b; string str=c; Print(c); }
В строгом режиме компиляции при несоответствии типов компилятор выводит предупреждения:
Рис.14. Предупреждения «possible loss of data due to type conversion» и «implicit conversion from ‘number’ to ‘string’
В данном примере компилятор предупреждает о возможной потере точности при присвоении различных типов данных и неявном преобразовании типа int в string.
Для исправления нужно использовать явное приведение типов:
#property strict void OnStart() { double a=7; float b=(float)a; int c=(int)b; string str=(string)c; Print(c); }
3.3. Неиспользуемые переменные
Наличие переменных, которые не используются в коде программы (лишние сущности) не является хорошим тоном.
void OnStart() { int i,j=10,k,l,m,n2=1; for(i=0; i<5; i++) {j+=i;} }
Сообщения о таких переменных выводятся вне зависимости от режима компиляции:
Рис.15. Предупреждения «variable ‘%’ not used’
Для исправления нужно убрать неиспользуемые переменные из кода программы.
Выводы
В статье рассмотрены типичные проблемы, с которыми могут столкнуться программисты при компиляции старых программ, содержащих ошибки.
Во всех случаях при отладке программ рекомендуется использовать строгий режим компиляции.
Предупреждение: все права на данные материалы принадлежат MetaQuotes Ltd. Полная или частичная перепечатка запрещена.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
Steviey opened this issue
Jan 13, 2019
· 5 comments
Closed
[RESOLVED] Implicit Conversion Warnings
#10
Steviey opened this issue
Jan 13, 2019
· 5 comments
Assignees
Comments
DWX_ZeroMQ_Server_v2.0.1_RC8
I get a bunch of warnings…actually can’t been overseen…
implicit conversion from ‘number’ to ‘string’ (multiple lines)
declaration of ‘data’ hides global declaration in file […] Z85.mqh (multiple lines)
expression not boolean GlobalVariable.mqh (multiple lines)
By the way, is this server version for Python only?
I can’t find any information, on how to handle the versions in regard to R.
And is it OK to use the old version because of its simple, easy to extend structur?
Thank you.
Hello Steviey,
The «implicit conversion from ‘number’ to ‘string'» is brought about in mql4 when you convert a number variable to a string variable in your code without explicitly coding it to do that. For example:
int number = 10;
Alert(number);
The above code will throw that warning. Instead, you should convert the the variable ‘number’ of type integer to type string. Like this:
int number = 10;
Alert(string(number));
Use the function string(); to remove those errors.
Hi @Steviey ,
Thank you for raising this — could you please do the following:
-
paste a text log of the warnings generated? need to ascertain which files are generating them, the MQL4 script for the EA itself, the dependencies, and/or both.
-
confirm which version / which file you are referencing here in this issue?
The latest MQL4 EA in v2.0.1_RC8 is language-neutral in the sense that you can implement the sequence of commands and send to the EA via any programming language of choice.
As long as the message is structured as the EA is expecting it in, the sending application could be any ZeroMQ supported language capable of digesting JSON responses.
We have not yet released a version for v2.0.1_RC8 in R, only Python.
Thanks!
[UPDATE] Implicit conversion warnings resolved in an updated DWX_ZeroMQ_Server_v2.0.1_RC8.mq4.
Changes will be committed shortly.
integracore2
changed the title
Bunch of Warnings
[RESOLVED] Bunch of Warnings
Jan 15, 2019
integracore2
changed the title
[RESOLVED] Bunch of Warnings
[RESOLVED] Implicit Conversion Warnings
Jan 15, 2019
На чтение 5 мин. Просмотров 103 Опубликовано 15.12.2019
Я делаю эту простую операцию со строкой в VB.NET
У меня есть строка информации, называемая segmentInfo выглядит так:
Поэтому я просто пытаюсь получить номер из него:
И я получаю на самом деле 2 предупреждения. Оба предупреждения указаны в одной строке кода.
Может быть, я мог понять первый, о string integer . но второй? Я не понимаю.
В любом случае, может кто-нибудь сказать мне, что я делаю неправильно и как это исправить?
string vb.net warnings implicit-conversion
Содержание
- 4 ответа
- 4 Answers 4
- Описание
- 1. Названия переменных с вспомогательными символами например . (точка)
- 2. Задекларированных переменных теперь больше, и переменные, которые были названы именами новых функций — требует изменения имени.
- 3. Каждая функция теперь должна иметь оператор возврата RETURN
- 4. Функция switсh в качестве выражения может принимать только Целые числа
- 5. Все переменные объявленные внутри функции, должны отличаться от названий глобальных переменных (Необязательно)
- 6. Все переменные, должны соответствовать по типу в используемых функциях
- 7. Сторонние библиотеки и функции , которые включают в себя передачу строк в DLL
- 8. Жесткий поиск ошибок #property strict
- 9. Все остальные ошибки и предупреждения решаются в индивидуальном порядке.
- 10. Еще один нюанс в 625 билде терминала мт4 should be checked
- 11. check operator precedence for possible error; use parentheses to clarify precedence
4 ответа
2 Решение Nico Schertler [2015-07-01 09:44:00]
Метод Split принимает Char (массив) как параметр, а не строку. Следовательно:
Во-вторых, вам нужно проанализировать полученную строку на целое число:
Сделайте это только тогда, когда вы знаете, что строка — это число. В противном случае используйте TryParse .
I currently have a generic class which allows the use of an expression as the value.
What I would like to be able to do is to set properties using implicit conversions from both T and from string. However if the expression is of type string, the compiler cannot decide which conversion to use.
Is there a clever way around this?
4 Answers 4
You won’t be able to keep both implicit operators and expect to work with an Expression because of the better conversion rule
Given an implicit conversion C1 that converts from a type S to a type T1, and an implicit conversion C2 that converts from a type S to a type T2, the better conversion of the two conversions is determined as follows:
- If T1 and T2 are the same type, neither conversion is better.
- If S is T1, C1 is the better conversion.
- If S is T2, C2 is the better conversion.
- If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion.
- If an implicit conversion from T2 to T1 exists, and no implicit conversion from T1 to T2 exists, C2 is the better conversion.
- If T1 is sbyte and T2 is byte, ushort, uint, or ulong, C1 is the better conversion.
- If T2 is sbyte and T1 is byte, ushort, uint, or ulong, C2 is the better conversion.
- If T1 is short and T2 is ushort, uint, or ulong, C1 is the better conversion.
- If T2 is short and T1 is ushort, uint, or ulong, C2 is the better conversion.
- If T1 is int and T2 is uint, or ulong, C1 is the better conversion.
- If T2 is int and T1 is uint, or ulong, C2 is the better conversion.
- If T1 is long and T2 is ulong, C1 is the better conversion.
- If T2 is long and T1 is ulong, C2 is the better conversion.
- Otherwise, neither conversion is better.
If an implicit conversion C1 is defined by these rules to be a better conversion than an implicit conversion C2, then it is also the case that C2 is a worse conversion than C1.
With an Expression you are clearly in the first case, the compiler won’t choose for you and will just stop there.
If there is not exactly one function member that is better than all other function members, then the function member invocation is ambiguous and a compile-time error occurs.
So you won’t be able to handle with with conversion operators only; either create additional methods to deal with string explicitly, convert the string to T outside of the operator or create a wrapping abstraction that would be able to tranport T, a string representation of T or the ExpressionText value and convert from it.
Описание
Новый язык программирования терминала МТ4 стал очень богатым. Он существенно расширил свои границы, здесь появились классы, ООП, графические элементы, новые операции с счетом, новые функции. Но и проблем с старым кодом здесь также присутствует.
1. Названия переменных с вспомогательными символами например . (точка)
2. Задекларированных переменных теперь больше, и переменные, которые были названы именами новых функций — требует изменения имени.
3. Каждая функция теперь должна иметь оператор возврата RETURN
4. Функция switсh в качестве выражения может принимать только Целые числа
5. Все переменные объявленные внутри функции, должны отличаться от названий глобальных переменных (Необязательно)
6. Все переменные, должны соответствовать по типу в используемых функциях
7. Сторонние библиотеки и функции , которые включают в себя передачу строк в DLL
8. Жесткий поиск ошибок #property strict
9. Все остальные ошибки и предупреждения решаются в индивидуальном порядке.
10. Еще один нюанс в 625 билде терминала мт4 should be checked
- return value of ‘OrderSelect’ should be checked
- return value of ‘OrderDelete’ should be checked
- return value of ‘OrderSend’ should be checked
- return value of ‘OrderClose’ should be checked
- return value of ‘OrderModify’ should be checked
для того, чтобы не было таких предупреждений нужно явно указать возврат в переменную
например так:
- bool select1=OrderSelect.
- bool delete1= OrderDelete .
- bool close1= OrderClose .
- bool modify1= OrderModify .
- int send1= OrderSend .
11. check operator precedence for possible error; use parentheses to clarify precedence
предупреждения касаются очередности операторов иили
например у Вас написано:
то предупреждение пропадет.
Т.е. если у Вас в условии написано и и и или или или , без скобок,
не хватает скобок, их нужно расставить правильно.
в декомпилированном коде это не совсем удобно, потому что от скобки зависит торговля всего эксперта.
Forum Rules |
|
100
File reading error
101
Error of opening an *. EX4 for writing
103
Not enough free memory to complete compilation
104
Empty syntactic unit unrecognized by compiler
105
Incorrect file name in #include
106
Error accessing a file in #include (probably the file does not exist)
108
Inappropriate name for #define
109
Unknown command of preprocessor (valid #include, #define, #property, #import)
110
Symbol unknown to compiler
111
Function not implemented (description is present, but no body)
112
Double quote («) omitted
113
Opening angle bracket (<) or double quote («) omitted
114
Single quote (‘) omitted
115
Closing angle bracket «>» omitted
116
Type not specified in declaration
117
No return operator or return is found not in all branches of the implementation
118
Opening bracket of call parameters was expected
119
Error writing EX4
120
Invalid access to an array
121
The function is not of void type and the return operator must return a value
122
Incorrect declaration of the destructor
123
Colon «:» is missing
124
Variable is already declared
125
Variable with such identifier already declared
126
Variable name is too long (> 250 characters)
127
Structure with such identifier already defined
128
Structure is not defined
129
Structure member with the same name already defined
130
No such structure member
131
Breached pairing of brackets
132
Opening parenthesis «(» expected
133
Unbalanced braces (no «}»)
134
Difficult to compile (too much branching, internal stack levels are overfilled)
135
Error of file opening for reading
136
Not enough memory to download the source file into memory
137
Variable is expected
138
Reference cannot be initialized
140
Assignment expected (appears at declaration)
141
Opening brace «{» expected
142
Parameter can be a dynamic array only
143
Use of «void» type is unacceptable
144
No pair for «)» or «]», i.e. «(or» [ » is absent
145
No pair for «(or» [ «, i.e. «) «or»] » is absent
146
Incorrect array size
147
Too many parameters (> 64)
149
This token is not expected here
150
Invalid use of operation (invalid operands)
151
Expression of void type not allowed
152
Operator is expected
153
Misuse of break
154
Semicolon «;» expected
155
Comma «,» expected
156
Must be a class type, not struct
157
Expression is expected
158
«non HEX character» found in HEX or too long number (number of digits> 511)
159
String-constant has more than 65534 characters
160
Function definition is unacceptable here
161
Unexpected end of program
162
Forward declaration is prohibited for structures
163
Function with this name is already defined and has another return type
164
Function with this name is already defined and has a different set of parameters
165
Function with this name is already defined and implemented
166
Function overload for this call was not found
167
Function with a return value of void type cannot return a value
168
Function is not defined
170
Value is expected
171
In case expression only integer constants are valid
172
The value of case in this switch is already used
173
Integer is expected
174
In #import expression file name is expected
175
Expressions are not allowed on global level
176
Omitted parenthesis «)» before «;»
177
To the left of equality sign a variable is expected
178
The result of expression is not used
179
Declaring of variables is not allowed in case
180
Implicit conversion from a string to a number
181
Implicit conversion of a number to a string
182
Ambiguous call of an overloaded function (several overloads fit)
183
Illegal else without proper if
184
Invalid case or default without a switch
185
Inappropriate use of ellipsis
186
The initializing sequence has more elements than the initialized variable
187
A constant for case expected
188
A constant expression required
189
A constant variable cannot be changed
190
Closing bracket or a comma is expected (declaring array member)
191
Enumerator identifier already defined
192
Enumeration cannot have access modifiers (const, extern, static)
193
Enumeration member already declared with a different value
194
There is a variable defined with the same name
195
There is a structure defined with the same name
196
Name of enumeration member expected
197
Integer expression expected
198
Division by zero in constant expression
199
Wrong number of parameters in the function
200
Parameter by reference must be a variable
201
Variable of the same type to pass by reference expected
202
A constant variable cannot be passed by a non-constant reference
203
Requires a positive integer constant
204
Failed to access protected class member
205
Import already defined in another way
208
Executable file not created
209
‘OnCalculate’ entry point not found for the indicator
210
The continue operation can be used only inside a loop
211
Error accessing private (closed) class member
213
Method of structure or class is not declared
214
Error accessing private (closed) class method
216
Copying of structures with objects is not allowed
218
Index out of array range
219
Array initialization in structure or class declaration not allowed
220
Class constructor cannot have parameters
221
Class destructor can not have parameters
222
Class method or structure with the same name and parameters have already been declared
223
Operand expected
224
Class method or structure with the same name exists, but with different parameters (declaration!=implementation)
225
Imported function is not described
226
ZeroMemory() is not allowed for objects with protected members or inheritance
227
Ambiguous call of the overloaded function (exact match of parameters for several overloads)
228
Variable name expected
229
A reference cannot be declared in this place
230
Already used as the enumeration name
232
Class or structure expected
235
Cannot call ‘delete’ operator to delete the array
236
Operator ‘ while’ expected
237
Operator ‘delete’ must have a pointer
238
There is ‘default’ for this ‘switch’ already
239
Syntax error
240
Escape-sequence can occur only in strings (starts with »)
241
Array required — square bracket ‘[‘ does not apply to an array, or non arrays are passed as array parameters
242
Can not be initialized through the initialization sequence
243
Import is not defined
244
Optimizer error on the syntactic tree
245
Declared too many structures (try to simplify the program)
246
Conversion of the parameter is not allowed
247
Incorrect use of the ‘delete’ operator
248
It’s not allowed to declare a pointer to a reference
249
It’s not allowed to declare a reference to a reference
250
It’s not allowed to declare a pointer to a pointer
251
Structure declaration in the list of parameter is not allowed
252
Invalid operation of typecasting
253
A pointer can be declared only for a class or structure
256
Undeclared identifier
257
Executable code optimizer error
258
Executable code generation error
260
Invalid expression for the ‘switch’ operator
261
Pool of string constants overfilled, simplify program
262
Cannot convert to enumeration
263
Do not use ‘virtual’ for data (members of a class or structure)
264
Cannot call protected method of class
265
Overridden virtual functions return a different type
266
Class cannot be inherited from a structure
267
Structure cannot be inherited from a class
268
Constructor cannot be virtual (virtual specifier is not allowed)
269
Method of structure cannot be virtual
270
Function must have a body
271
Overloading of system functions (terminal functions) is prohibited
272
Const specifier is invalid for functions that are not members of a class or structure
274
Not allowed to change class members in constant method
276
Inappropriate initialization sequence
277
Missed default value for the parameter (specific declaration of default parameters)
278
Overriding the default parameter (different values in declaration and implementation)
279
Not allowed to call non-constant method for a constant object
280
An object is necessary for accessing members (a dot for a non class/structure is set)
281
The name of an already declared structure cannot be used in declaration
284
Unauthorized conversion (at closed inheritance)
285
Structures and arrays cannot be used as input variables
286
Const specifier is not valid for constructor/destructor
287
Incorrect string expression for a datetime
288
Unknown property (#property)
289
Incorrect value of a property
290
Invalid index for a property in #property
291
Call parameter omitted — <func (x,)>
293
Object must be passed by reference
294
Array must be passed by reference
295
Function was declared as exportable
296
Function was not declared as exportable
297
It is prohibited to export imported function
298
Imported function cannot have this parameter (prohibited to pass a pointer, class or structure containing a dynamic array, pointer, class, etc.)
299
Must be a class
300
#import was not closed
302
Type mismatch
303
Extern variable is already initialized
304
No exported function or entry point found
305
Explicit constructor call is not allowed
306
Method was declared as constant
307
Method was not declared as constant
308
Incorrect size of the resource file
309
Incorrect resource name
310
Resource file opening error
311
Resource file reading error
312
Unknown resource type
313
Incorrect path to the resource file
314
The specified resource name is already used
315
Argument expected for the function-like macro
316
Unexpected symbol in macro definition
317
Error in formal parameters of the macro
318
Invalid number of parameters for a macro
319
Too many parameters for a macro
320
Too complex, simplify the macro
321
Parameter for EnumToString() can be only an enumeration
322
The resource name is too long
323
Unsupported image format (only BMP with 24 or 32 bit color depth is supported)
324
An array cannot be declared in operator
325
The function can be declared only in the global scope
326
The declaration is not allowed for the current scope
327
Initialization of static variables with the values of local variables is not allowed
328
Illegal declaration of an array of objects that do not have a default constructor
329
Initialization list allowed only for constructors
330
No function definition after initialization list
331
Initialization list is empty
332
Array initialization in a constructor is not allowed
333
Initializing members of a parent class in the initialization list is not allowed
334
Expression of the integer type expected
335
Memory required for the array exceeds the maximum value
336
Memory required for the structure exceeds the maximum value
337
Memory required for the variables declared on the global level exceeds the maximum value
338
Memory required for local variables exceeds the maximum value
339
Constructor not defined
340
Invalid name of the icon file
341
Could not open the icon file at the specified path
342
The icon file is incorrect and is not of the ICO format
343
Reinitialization of a member in a class/structure constructor using the initialization list
344
Initialization of static members in the constructor initialization list is not allowed
345
Initialization of a non-static member of a class/structure on a global level is not allowed
346
The name of the class/structure method matches the name of an earlier declared member
347
The name of the class/structure member matches the name of an earlier declared method
348
Virtual function cannot be declared as static
349
The const modifier is not allowed for static functions
350
Constructor or destructor cannot be static
351
Non-static member/method of a class or a structure cannot be accessed from a static function
352
An overload operation (+,-,[],++,— etc.) is expected after the operator keyword
353
Not all operations can be overloaded in MQL4
354
Definition does not match declaration
355
An invalid number of parameters is specified for the operator
356
Event handling function not found
357
Method cannot be exported
358
A pointer to the constant object cannot be normalized by a non-constant object
359
Class templates are not supported yet
360
Function template overload is not supported yet
361
Function template cannot be applied
362
Ambiguous parameter in function template (several parameter types can be applied)
363
Unable to determine the parameter type, by which the function template argument should be normalized
364
Incorrect number of parameters in the function template
365
Function template cannot be virtual
366
Function templates cannot be exported
367
Function templates cannot be imported
368
Structures containing the objects are not allowed
369
String arrays and structures containing the objects are not allowed
370
A static class/structure member must be explicitly initialized
371
Compiler limitation: the string cannot contain more than 65 535 characters
372
Inconsistent #ifdef/#endif
373
Object of class cannot be returned, copy constructor not found
374
Non-static members and methods cannot be used
375
OnTesterInit() impossible to use without OnTesterDeinit()
376
Redefinition of formal parameter ‘%s’
377
Macro __FUNCSIG__ and __FUNCTION__ cannot appear outside of a function body
378
Invalid returned type. For example, this error will be produced for functions imported from DLL that return structure or pointer.
379
Template usage error
380
Not used
381
Illegal syntax when declaring pure virtual function, only «=NULL» or «=0» are allowed
382
Only virtual functions can be declared with the pure-specifier («=NULL» or «=0»)
383
Abstract class cannot be instantiated
384
A pointer to a user-defined type should be applied as a target type for dynamic casting using the dynamic_cast operator
385
«Pointer to function» type is expected
386
Pointers to methods are not supported
387
Error — cannot define the type of a pointer to function
388
Type cast is not available due to private inheritance
389
A variable with const modifier should be initialized during declaration