eganator 71 / 51 / 8 Регистрация: 13.11.2017 Сообщений: 372 |
||||
1 |
||||
11.01.2022, 13:30. Показов 1211. Ответов 4 Метки нет (Все метки)
Здравствуйте! В 16 строке переменные height и width не определены. Но мне нужно передать их подобным образом. Подскажите, пожалуйста, как это можно сделать правильно?
__________________
0 |
8719 / 4299 / 958 Регистрация: 15.11.2014 Сообщений: 9,744 |
|
11.01.2022, 14:02 |
2 |
В 16 строке переменные height и width не определены. это — неправда. твоя проблема заключается вовсе не в неопределенности имен.
error C2131: выражение не определяется константой переменные обязаны быть константами времени компиляции.
как это можно сделать правильно? можно заменить компилятор Visual Studio на gcc.
придется код переписывать.
1 |
71 / 51 / 8 Регистрация: 13.11.2017 Сообщений: 372 |
|
11.01.2022, 14:15 [ТС] |
3 |
hoggy, спасибо! Смена компилятора помогла, всё стало работать как надо.
0 |
7423 / 5018 / 2890 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
11.01.2022, 15:20 |
4 |
как это можно сделать правильно? замените статический массив (строка 16) на динамический
0 |
8719 / 4299 / 958 Регистрация: 15.11.2014 Сообщений: 9,744 |
|
11.01.2022, 15:46 |
5 |
замените статический массив (строка 16) на динамический у ТС в программе — автоматический массив.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
11.01.2022, 15:46 |
Помогаю со студенческими работами здесь Error C2099: инициализация не является константой #ifndef PROC_DB FILE *fp; /* Вывести значение логического выражения, заданного в виде строки S. Выражение определяется следующим образом («T» — True, «F» — False): <выражение> : Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется следующим образом Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется следующим образом (функция M воз-вращает максимальный из Error C2057: требуется константное выражение Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords |
---|---|---|---|---|
Learn more about: Compiler Error C2131 |
Compiler Error C2131 |
02/28/2019 |
C2131 |
C2131 |
Compiler Error C2131
expression did not evaluate to a constant
An expression declared as const
or constexpr
didn’t evaluate to a constant at compile time. The compiler must be able to determine the value of the expression at the point it’s used.
Example
This example shows a way to cause error C2131, and how to fix it.
// c2131.cpp // compile by using: cl /EHsc /W4 /c c2131.cpp struct test { static const int array_size; // To fix, init array_size here. int size_array[array_size]; // C2131 }; const int test::array_size = 42;
c2131.cpp
c2131.cpp(7): error C2131: expression did not evaluate to a constant
c2131.cpp(7): note: failure was caused by non-constant arguments or reference to a non-constant symbol
c2131.cpp(7): note: see usage of 'array_size'
See also
const
constexpr
// foo.hpp file
class foo
{
public:
static const int nmConst;
int arr[nmConst]; // line 7
};
// foo.cpp file
const int foo::nmConst= 5;
Compiler VC 2015 return error:
1>foo.h(7): error C2131: expression did not evaluate to a constant
1> 1>foo.h(7): failure was caused by non-constant arguments or
reference to a non-constant symbol 1> 1>foo.h(7): note: see usage of
‘nmConst’
Why? nmConst is static constant with value defined in *.cpp file.
asked Nov 10, 2015 at 7:54
0
It’s possible to use static const int
member as an array size, but you’ll have to define this member within class in your .hpp file like so:
class foo
{
public:
static const int nmConst = 10;
int arr[nmConst];
};
This will work.
P.S. About the logic behind it, I believe compiler wants to know size of the array member as soon as it encounters class declaration. If you leave static const int
member undefined within the class, compiler will understand that you’re trying to define variable-length array and report an error (it won’t wait to see if you actually defined nmconst
someplace).
answered Nov 10, 2015 at 8:07
dbajgoricdbajgoric
1,44711 silver badges17 bronze badges
0
Ошибки компилятора с C2100 по C2199
В статьях в этом разделе документации объясняется подмножество сообщений об ошибках, создаваемых компилятором.
Компиляторы и средства сборки Visual Studio могут сообщать о различных типах ошибок и предупреждений. После обнаружения ошибки или предупреждения средства сборки могут делать предположения о намерении кода и пытаться продолжить работу, чтобы можно было сообщать о дополнительных проблемах одновременно. Если средства делают неверное предположение, последующие ошибки или предупреждения не могут применяться к проекту. При устранении проблем в проекте всегда начинайте с первой зарегистрированной ошибки (или предупреждения) и выполняйте повторную сборку как можно чаще. Одно исправление может привести к возникновению многих последующих ошибок.
Чтобы получить справку о конкретном диагностическом сообщении в Visual Studio, выберите его в окне вывода и нажмите клавишу F1 . Visual Studio открывает страницу документации для этой ошибки, если она существует. Вы также можете использовать средство поиска в верхней части страницы, чтобы найти статьи о конкретных ошибках или предупреждениях. Кроме того, просмотрите список ошибок и предупреждений по инструменту и введите оглавление на этой странице.
Не все ошибки или предупреждения Visual Studio описаны. Во многих случаях диагностическое сообщение предоставляет все доступные сведения. Если вы приземлились на этой странице при использовании F1 и считаете, что сообщение об ошибке или предупреждении требует дополнительного объяснения, сообщите нам об этом. Кнопки обратной связи на этой странице можно использовать для создания проблемы с документацией на сайте GitHub. Если вы считаете, что ошибка или предупреждение неправы или обнаружена другая проблема с набором инструментов, сообщите о проблеме с продуктом на сайте Сообщество разработчиков. Вы также можете отправить отзыв и ввести ошибки в интегрированной среде разработки. В Visual Studio перейдите в строку меню и выберите «Отправить > отзыв справки>» или отправьте предложение с помощью отправки > отзывов > справки.
Вы можете найти дополнительную помощь по ошибкам и предупреждениям на форумах Microsoft Learn Q&A . Или найдите номер ошибки или предупреждения на сайте Сообщество разработчиков Visual Studio C++. Вы также можете выполнить поиск решений в Stack Overflow .
Ссылки на дополнительные справочные материалы и ресурсы сообщества см. в справке и сообществе Visual C++.
Источник
Error c2131 выражение не определяется константой
Профиль
Группа: Участник
Сообщений: 2
Регистрация: 16.3.2016
Репутация: нет
Всего: нет
Сгенерировать и вывести на экран массив с 10 рандомных чисел от -50 до 50. Положительные элементы массива перенести в другой массив №1, а отрицательные в другой №2.
#include «stdafx.h»
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
<
int *mas, n;
cout > n;
mas = new int[n];
int positiv = 0, negativ = 0;
for (int j = 0; j 0)
positiv++;
>
int *mas_p = new int[positiv];
int *mas_n = new int[negativ];
stargame |
|
||
|
rudolfninja |
|
||
Опытный Профиль Репутация: 1 Вы код забыли полностью дописать. Это сообщение отредактировал(а) rudolfninja — 16.3.2016, 21:18 |
|||
|
baldman88 |
|
||
Бывалый Профиль Репутация: 1
int _tmain(int argc, _TCHAR* argv[]) |
disputant |
|
||
Бывалый Профиль Репутация: нет
|
|||
|
Профиль
Группа: Участник
Сообщений: 26
Регистрация: 4.6.2015
Репутация: нет
Всего: нет
dreindeimos |
|
||
|
baldman88 |
|
||
Бывалый Профиль Репутация: 1
|
|||
|
disputant |
|
|||
Бывалый Профиль Репутация: нет
Берем последний Visual C++ 2015.
Имеем: error C2131: выражение не определяется константой Витая в эмпиреях, вы можете использовать распоследний стандарт, но компилировать вы будете на земле реальным компилятором. |
||||
|
baldman88 |
|
||
Бывалый Профиль Репутация: 1
Витая в эмпиреях, вы можете использовать распоследний стандарт, но компилировать вы будете на земле реальным компилятором. |
Искренне Вам сочувствую . Свет не сошелся клином на поделиях MS.
Это сообщение отредактировал(а) baldman88 — 19.3.2016, 00:09
disputant |
|
||
Бывалый Профиль Репутация: нет
Витая в эмпиреях, вы можете использовать распоследний стандарт, но компилировать вы будете на земле реальным компилятором. |
Искренне Вам сочувствую . Свет не сошелся клином на поделиях MS.
А если вы по gcc — так в нем, на котором, видимо, у вас свет сошшелся, это расширение было уже очень давно.
Если вам не трудно, приведите еще 2-3 примера компиляторов, которые это скомпилируют. Просто чтоб понимать, до какой степени отстой этот Microsoft, и что все остальные давно умеют делать такие стандартные вещи.
Забавно, что отстойный сайт http://en.cppreference.com/w/cpp/language/array утверждает, что даже с C++14 там должно быть константное выражение, известное во время компиляции.
P.S. Полез в стандарт — п. 8.3.4,
In a declaration T D where D has the form
D1 [ constant-expressionopt] attribute-specifier-seqopt
Так что свет клином, надо понимать, и на стандарте не сошелся.
Это сообщение отредактировал(а) disputant — 19.3.2016, 19:01
baldman88 |
|
||
Бывалый Профиль Репутация: 1 Ваш ник говорит сам за себя Вы попросили назвать еще 2-3 примера компиляторов . Давайте начнем с того, что я знаю всего 4 самых распространенных компилятора. Остальное, субъективно, это экзотика. Вычтем из этих четырех озвученные Вами gcc и vc. Остается всего 2. Из них clang точно поддерживает. За интеловский ничего не скажу. Это сообщение отредактировал(а) baldman88 — 20.3.2016, 02:20 |
|||
|
disputant |
|
||
Бывалый Профиль Репутация: нет
Даже Страуструп пишет, что очень большая ошибка — считать С++ расширением языка C. А посему — особенно в ответах для начинающих и для переносимости — я считаю, что нужно использовать стандарт, а любые от него отклонения документировать Что до последнего пожелания. Считаю, что как раз начинающим будет полезнее рассказывать, пусть и не подробно, но со всей строгостью закона. Да, это обычно трудно, но — взялся за гуж. |
|||
|
_zorn_ |
|
||
Эксперт Профиль Репутация: нет
|
|||
|
baldman88 |
|
||||||
Бывалый Профиль Репутация: 1
Это конечно хорошо, что Вы так сведущи в стандарте. Я подробно его не читал (кроме некоторых моментов). Но для работы я по максимуму пользуюсь удобствами, предоставляемыми инструментами, которыми я пользуюсь. Ну и по порядку: Это сообщение отредактировал(а) baldman88 — 21.3.2016, 09:33
1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.
[ Время генерации скрипта: 0.1377 ] [ Использовано запросов: 21 ] [ GZIP включён ] Источник Adblock |
// foo.hpp file
class foo
{
public:
static const int nmConst;
int arr[nmConst]; // line 7
};
// foo.cpp file
const int foo::nmConst= 5;
Ошибка возврата компилятора VC 2015:
1> foo.h (7): ошибка C2131: выражение не было константой
1> 1> foo.h (7): сбой был вызван непостоянными аргументами или
ссылка на непостоянный символ 1> 1> foo.h (7): примечание: см. использование
‘NmConst’
Зачем? nmConst — статическая константа со значением, определенным в файле * .cpp.
1
Решение
Можно использовать static const int
member как размер массива, но вы должны будете определить этот член внутри класса в вашем файле .hpp следующим образом:
class foo
{
public:
static const int nmConst = 10;
int arr[nmConst];
};
Это будет работать
Постскриптум Что касается логики этого, я полагаю, что компилятор хочет знать размер члена массива, как только он встречает объявление класса. Если ты уйдешь static const int
В классе не определен член, компилятор поймет, что вы пытаетесь определить массив переменной длины и сообщит об ошибке (он не будет ждать, если вы действительно определили nmconst
где-то).
5
Другие решения
Других решений пока нет …
<The previous article in this series | The table of contents of this series | The next article in this series>
The error against using a class static ‘const’ field as an array size. The new (arguably) right way to define any class static integral field is here.
Topics
About:
C++
The table of contents of this article
- Starting Context
- Target Context
- Main Body
- 1: Meeting the «C2131: expression did not evaluate to a constant» Visual C++ Compile Error
- 2: The Term, «constant», Is Sloppily Used There
- 3: Why the Array Size Is Not Compile-Time Determined
- 4: The New (Arguably) Right Way to Define Any Class Static Integral Field
- 5: But Why Only Integral Fields? A Complaint
Starting Context
- The reader has a basic knowledge on C++.
Target Context
- The reader will know how to solve the «C2131: expression did not evaluate to a constant» Visual C++ compile error and more generally, the new (arguably) right way to define any class static integral field.
Main Body
1: Meeting the «C2131: expression did not evaluate to a constant» Visual C++ Compile Error
Hypothesizer 7
«C2131: expression did not evaluate to a constant»?
Well, I am trying to compile this piece of C++ code with Visual C++.
theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/TestConstantsGroup.hpp
@C++ Source Code
#ifndef __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_TestConstantsGroup_hpp__
#define __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_TestConstantsGroup_hpp__
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
class TestConstantsGroup {
public:
static int const c_smallBufferSize;
};
}
}
}
#endif
theBiasPlanet/coreUtilitiesTests/staticVariablesInitializer/StaticVariablesInitializer.cpp
@C++ Source Code
#include "theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/TestConstantsGroup.hpp"
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
int const TestConstantsGroup::c_smallBufferSize = 1024;
}
}
}
theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/Test1Test.hpp
@C++ Source Code
#ifndef __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_Test1Test_hpp__
#define __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_Test1Test_hpp__
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
class Test1Test {
public:
static int main (int const & a_argumentsNumber, char const * const a_arguments []);
static void test ();
};
}
}
}
#endif
theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/Test1Test.cpp
@C++ Source Code
#include "theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/Test1Test.hpp"
#include "theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/TestConstantsGroup.hpp"
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
int Test1Test::main (int const & a_argumentsNumber, char const * const a_arguments []) {
return 0;
}
void Test1Test::test () {
char l_smallBuffer [TestConstantsGroup::c_smallBufferSize];
}
}
}
}
«did not evaluate to a constant»? . . . While the error points to the size specification of the ‘l_smallBuffer’ array, ‘TestConstantsGroup::c_smallBufferSize’ is certainly constant, right?
2: The Term, «constant», Is Sloppily Used There
Hypothesizer 7
C++ is notorious for its sloppy terminology. «lvalue», etc., «move semantics», etc., and «static» are some examples.
There, in that error message, «constant» is sloppily used.
That error message seems to mean that the array size is not ‘compile-time determined’. Then, please say so.
Note that GCC does not report that error, because GCC does not require any array size to be compile-time determined.
3: Why the Array Size Is Not Compile-Time Determined
Hypothesizer 7
The reason why the array size is not compile-time determined is that any C++ source file is separately compiled.
‘Test1Test.cpp’ is compiled by itself, without ‘StaticVariablesInitializer.cpp’ (which determines the class static field value) being refered to. So, the compiler cannot know the value at compile-time.
4: The New (Arguably) Right Way to Define Any Class Static Integral Field
Hypothesizer 7
Then, what am I supposed to do?
The above way to define any class static field is something introduced in an old textbook I have. Rereading the book, in fact, I now have found that the book mentions the problem. The solution the book proposes is to use an ‘enum’ instead.
Well, I see, but I do not like it very much: it is not along the original purpose of ‘enum’, I think.
In fact, nowadays (I do not know exactly from when), the class static integral field can be declared and defined like this.
theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/TestConstantsGroup.hpp
@C++ Source Code
#ifndef __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_TestConstantsGroup_hpp__
#define __theBiasPlanet_coreUtilitiesTests_classStaticFieldTest1_TestConstantsGroup_hpp__
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
class TestConstantsGroup {
public:
static int const c_smallBufferSize = 1024;
};
}
}
}
#endif
theBiasPlanet/coreUtilitiesTests/staticVariablesInitializer/StaticVariablesInitializer.cpp
@C++ Source Code
#include "theBiasPlanet/coreUtilitiesTests/classStaticFieldTest1/TestConstantsGroup.hpp"
namespace theBiasPlanet {
namespace coreUtilitiesTests {
namespace classStaticFieldTest1 {
int const TestConstantsGroup::c_smallBufferSize;
}
}
}
Does that solve the problem? Yes: as the value is written in the header file, the array size is determined at the ‘Test1Test.cpp’ compile-time.
That is better than employing a dirty trick like using ‘enum’, or using a macro, more dirty.
5: But Why Only Integral Fields? A Complaint
Hypothesizer 7
But that way is allowed for only integral (which means not only ‘int’ but also ‘unsigned int’, ‘short’, ‘byte’, etc., but not ‘double’, ‘::std::string’, etc.) fields. Why? . . . I do not see the reason.
I complain because such a restriction causes unreasonable inconsistency in defining class static fields: sometimes, I can set the value in the header file, and at the other times, I have to set the value in the source file.
We should raise complaints on unreasonable specifications.
References
<The previous article in this series | The table of contents of this series | The next article in this series>
I’m trying to compile the following snippet with VS2017 but it is throwing an error C2131: expression did not evaluate to a constant
without any further detail in the output log.
class Example
{
public:
constexpr Example() : m_int()
{
for (int i = 0; i < 256; ++i)
{
for (int j = 0; j < 256; ++j)
{
m_int[i] = i;
}
}
}
private:
int m_int[256];
};
int main()
{
constexpr Example vv; // <-- error C2131 here
return 0;
}
However for some reason unknown to me, if I stop the j counter at < 255
(instead of 256), the code compile fine.
What’s the explanation behind this and how can I fix it?
asked Dec 7, 2019 at 4:44
4
Further searching landed me on the following link and after some trial and error with the parameters values I found the solution.
Adding /constexpr:steps10000000
to the project additional options in C++ compiler settings has fixed the error and now it compiles fine. I wish VS2017 would throw the error C4593 in this case instead of C2131 as it would have saved me a headache!
answered Dec 7, 2019 at 5:14
RobotexRobotex
1051 gold badge2 silver badges10 bronze badges
I’m trying to compile the following snippet with VS2017 but it is throwing an error C2131: expression did not evaluate to a constant
without any further detail in the output log.
class Example
{
public:
constexpr Example() : m_int()
{
for (int i = 0; i < 256; ++i)
{
for (int j = 0; j < 256; ++j)
{
m_int[i] = i;
}
}
}
private:
int m_int[256];
};
int main()
{
constexpr Example vv; // <-- error C2131 here
return 0;
}
However for some reason unknown to me, if I stop the j counter at < 255
(instead of 256), the code compile fine.
What’s the explanation behind this and how can I fix it?
asked Dec 7, 2019 at 4:44
4
Further searching landed me on the following link and after some trial and error with the parameters values I found the solution.
Adding /constexpr:steps10000000
to the project additional options in C++ compiler settings has fixed the error and now it compiles fine. I wish VS2017 would throw the error C4593 in this case instead of C2131 as it would have saved me a headache!
answered Dec 7, 2019 at 5:14
RobotexRobotex
1051 gold badge2 silver badges10 bronze badges