Ошибка c2131 выражение не определяется константой

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 не определены. Но мне нужно передать их подобным образом. Подскажите, пожалуйста, как это можно сделать правильно?

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <conio.h>
#include <string>
#include <windows.h>
using namespace std;
 
string encript(string message, int width) {
    int height;
    if (message.length() % width != 0) {
        height = message.length() / width + 1;
    }
    else {
        height = message.length() / width;
    }
 
    char table[height][width];
    int k;
 
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            if (k < message.length())
            {
                table[i][j] = message[k];
                k++;
            }
            else table[i][j] = ' ';
        }
    }
 
    string code;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            code += table[j][i];
        }
    }
    return code;
}
 
int main() {
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
 
    string text;
    cout << "Введите текст: ";
    getline(cin, text);
    int key;
    cout << "Ключ (ширина таблицы): ";
    cin >> key;
    cout << "Зашифрованный текст: ";
    encript(text, key);
 
    _getch();
    return 0;
}



0



Эксперт С++

8725 / 4305 / 958

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

Сообщений: 9,752

11.01.2022, 14:02

2

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

В 16 строке переменные height и width не определены.

это — неправда.
имена height и width становятся определенными в 7 и 8 строках.

твоя проблема заключается вовсе не в неопределенности имен.
она заключается вот в этом:

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

error C2131: выражение не определяется константой

переменные обязаны быть константами времени компиляции.
но они у тебя таковыми не являются.

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

как это можно сделать правильно?

можно заменить компилятор 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

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

как это можно сделать правильно?

замените статический массив (строка 16) на динамический



0



Эксперт С++

8725 / 4305 / 958

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

Сообщений: 9,752

11.01.2022, 15:46

5

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

замените статический массив (строка 16) на динамический

у ТС в программе — автоматический массив.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

11.01.2022, 15:46

Помогаю со студенческими работами здесь

Error C2099: инициализация не является константой
proc_db.h

#ifndef PROC_DB
#define PROC_DB

FILE *fp;
int errors;

/*

Вывести значение логического выражения, заданного в виде строки S. Выражение определяется следующим образом («T» — True, «F» — False): <выражение> :
помогите пожалуйста решить задачку на рекурсию
Вывести значение логического выражения, заданного…

Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется следующим образом
Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется…

Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется следующим образом (функция M воз-вращает максимальный из
Вывести значение целочисленного выражения, заданного в виде строки S. Выражение определяется…

Error C2057: требуется константное выражение
Добрый день!
Помогите разобраться с ошибками, все ругаются на одну строку int c_max_ind = -1, ans,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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.

Raktim Biswas's user avatar

asked Nov 10, 2015 at 7:54

user3437441's user avatar

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

dbajgoric's user avatar

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 13

Warning C26498 — The function ‘myInt’ is constexpr, mark variable ‘val2’
constexpr if compile-time evaluation is desired (con.5). line 14

Error 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)

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка c3100 kyocera fs 1025
  • Ошибка c2131 kia rio
  • Ошибка c3100 kyocera 1135
  • Ошибка c2130 kia ceed

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии