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
eganator 71 / 51 / 8 Регистрация: 13.11.2017 Сообщений: 372 |
||||
1 |
||||
11.01.2022, 13:30. Показов 1747. Ответов 4 Метки нет (Все метки)
Здравствуйте! В 16 строке переменные height и width не определены. Но мне нужно передать их подобным образом. Подскажите, пожалуйста, как это можно сделать правильно?
0 |
8725 / 4305 / 958 Регистрация: 15.11.2014 Сообщений: 9,752 |
|
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 |
7427 / 5021 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
11.01.2022, 15:20 |
4 |
как это можно сделать правильно? замените статический массив (строка 16) на динамический
0 |
8725 / 4305 / 958 Регистрация: 15.11.2014 Сообщений: 9,752 |
|
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 |
// 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
I am trying to learn about const
and constexpr
and have run into the error C26498 on VS2019. However, my example is almost the same as described here:
constexpr int myInt();
constexpr int getMyValue();
void foo();
int main()
{
int val1 = myInt(); // C26498 warning (mark variable constexpr)
const int val2 = myInt(); // C26498 warning (mark variable constexpr)
constexpr int val3 = myInt(); // C2131 error (expression did not evaluate to a constant)
foo();
}
constexpr int myInt() { return 1; }
constexpr int getMyValue() { return 1; }
void foo() { constexpr int val0 = getMyValue(); // no C26498 }
Edit: As requested, here is the error list (VS2019):
Warning C26498 — The function ‘myInt’ is constexpr, mark variable ‘val1’
constexpr if compile-time evaluation is desired (con.5). line 13Warning C26498 — The function ‘myInt’ is constexpr, mark variable ‘val2’
constexpr if compile-time evaluation is desired (con.5). line 14Error C2131 — expression did not evaluate to a constant line 15
Message — failure was caused by call of undefined function or one not
declared ‘constexpr’ line 15
I do understand the warnings for val1
and val2
, but then when I do use constexpr
for val3
, I get an error. Why does this throw an error when almost the same code, encapsulated in another function (foo()
) doesn’t? From my (limited) understanding, can’t myInt()
also be computed at compile time?
// 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
Другие решения
Других решений пока нет …
У меня есть ниже код:
Clustering::Clustering( VectorIntPtr locus_encoding ){
// Allocate memory and initialise
_cluster_assignment = allocate_VectorInt( PROBLEM->ndata() );
for( int i=0; i<PROBLEM->ndata(); i++ ){ _cluster_assignment[ i ] = -1; }
_total_clusters = 0; // Total number of clusters found
int previous[ PROBLEM->ndata() ];
// Get assinment of each data element to a cluster
// Each connected component of the graph (as encoded in the adjacency-base encoding)
// represents a different cluster
for( int i=0; i<PROBLEM->ndata(); i++ ){
int ctr = 0;
// Unassigned element found, assign cluster
if( _cluster_assignment[ i ] == -1 ){
// Assign to cluster, keep track of it,
// and identify neighbour (adjacent element)
_cluster_assignment[ i ] = _total_clusters;
previous[ ctr++ ] = i;
int neighbour = locus_encoding[ i ];
// Repeat operation for consecutive neighboring elements
// and assign to the same cluster
while( _cluster_assignment[ neighbour ] == -1 ){
_cluster_assignment[ neighbour ] = _total_clusters;
previous[ ctr++ ] = neighbour;
neighbour = locus_encoding[ neighbour ];
}
// If a previously assigned neighbour is reached,
// and this element was assigned to a different cluster X,
// re-assign all elements in 'previous' list to cluster X
if( _cluster_assignment[ neighbour ] != _total_clusters ){
while( --ctr >= 0 ){
_cluster_assignment[ previous[ ctr ] ] = _cluster_assignment[ neighbour ];
}
}else{
// Increase cluster counter
_total_clusters++;
}
}
}
// Centroid computation
compute_cluster_centres();
}
Но в этой строке int previous[ PROBLEM->ndata() ];
поймите меня ниже ошибка:
error C2131: expression did not evaluate to a constant
И, скажем, ошибка была вызвана непостоянными аргументами или ссылкой на непостоянный символ, и обратите внимание: см. Использование «ПРОБЛЕМА».
В моем A.hh
я заявляю как ниже:
ClusteringProblemPtr PROBLEM;
И в mock_ClusteringProblem.fwd.hh
это как mock_ClusteringProblem.fwd.hh
ниже:
#ifndef __MOCK_CLUSTERINGPROBLEM_FWD_HH__
#define __MOCK_CLUSTERINGPROBLEM_FWD_HH__class ClusteringProblem;
typedef ClusteringProblem * ClusteringProblemPtr;
#endif
Что я могу сделать?
(Я использую из Microsoft Visual Studio 2017 — версия 15.9.6)