Skip to content

Clean up C2397 #4743

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

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions docs/error-messages/compiler-errors-1/compiler-error-c2397.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,22 @@ The C language allows implicit narrowing conversions in assignments and initiali

A narrowing conversion can be okay when you know the possible range of converted values can fit in the target. In this case, you know more than the compiler does. If you make a narrowing conversion intentionally, make your intentions explicit by using a static cast. Otherwise, this error message almost always indicates you have a bug in your code. You can fix it by making sure the objects you initialize have types that are large enough to handle the inputs.

The following sample generates C2397 and shows one way to fix it:

```
// C2397.cpp -- C++ narrowing conversion diagnostics
// Compile by using: cl /EHsc C2397.cpp
#include <vector>

struct S1 {
int m1;
double m2, m3;
The following sample generates C2397:

```cpp
// C2397.cpp
// compile with: /c
struct S {
int m1;
double m2, m3;
};

void function_C2397(double d1) {
char c1 { 127 }; // OK
char c2 { 513 }; // error C2397

std::vector<S1> vS1;
vS1.push_back({ d1, 2, 3 }); // error C2397

// Possible fix if you know d1 always fits in an int
vS1.push_back({ static_cast<int>(d1), 2, 3 });
void func(double d1) {
char c1 { 127 }; // OK
char c2 { 513 }; // C2397

S arr[2]{};
arr[0] = { d1, 2.0, 3.0 }; // C2397
arr[1] = { static_cast<int>(d1), 2.0, 3.0 }; // OK
}
```