Polyspace: expression must have a constant value

8 ビュー (過去 30 日間)
Zulham Mr
Zulham Mr 2022 年 4 月 28 日
コメント済み: Zulham Mr 2022 年 5 月 3 日
Hello guys,
I have this C++17 code:
#define I2C_BUS_MAX_BUS_ITEMS 3
struct my_bus_t {
int bus{-1};
bool is_external;
};
static inline constexpr my_bus_t initBus(int bus)
{
my_bus_t ret{};
ret.bus = bus;
ret.is_external = false;
return ret;
}
constexpr my_bus_t buses[I2C_BUS_MAX_BUS_ITEMS] = {
initBus(1),
initBus(2),
};
This is the configuration setting.
It compiles well, but there is a problem in Polyspace: "expression must have a constant value".
Thank you in advance.
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 4 月 28 日
Which expression is it flagging?
Zulham Mr
Zulham Mr 2022 年 4 月 28 日
constexpr my_bus_t buses[I2C_BUS_MAX_BUS_ITEMS] = {
initBus(1),
initBus(2),
};
This one.

サインインしてコメントする。

採用された回答

Anirban
Anirban 2022 年 4 月 29 日
編集済み: Anirban 2022 年 4 月 29 日
You are initializing a three-element constexpr array with only two elements. If you change the line:
constexpr my_bus_t buses[I2C_BUS_MAX_BUS_ITEMS] = {
initBus(1),
initBus(2),
};
To something like:
constexpr my_bus_t buses[I2C_BUS_MAX_BUS_ITEMS] = {
initBus(1),
initBus(2),
initBus(2)
};
The error will go away. I am not sure why your compiler did not flag this.
  3 件のコメント
Anirban
Anirban 2022 年 5 月 2 日
The C++ reference for constexpr states that constexpr variables must be immediately initialized.
In this case, you have partially initialized the array. This is not an error by itself, and my guess is, that is why the compiler does not complain. If you try to initialize the uninitialized elements later, the compiler should show an error.
Indeed, Polyspace is being stricter than your compiler. But, as you can see, partially initializing a constexpr array is an error because it cannot be initialized fully later.
Zulham Mr
Zulham Mr 2022 年 5 月 3 日
Thank you for your explanation.

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by