Visual Studio 2019 C++: Why do char and string literals with non-ASCII characters have different values depending on the source file?

Frederic Reinhardt 21 Reputation points
2022-05-16T04:14:58.063+00:00

Why does the value of c after the assignment

char c='ü';

depend on whether it appears in the source file 'CharTest.cpp' with the main()-function or in a different source file?

You can test this in Visual Studio 2019 with the following 3 files for which i get the output
f: -4
main: -68

even though the values should be the same.

// TU.h
void f();

// TU.cpp
#include <iostream>
void f()
{
    char c = 'ü';
    int i(c);
    std::cout << "f: " << i << "\n";
    return;
}

//  CharTest.cpp
#include <iostream>
#include "TU.h"

int main()
{
    char c = 'ü';
    f();

    int i(c);

    std::cout << "main: " << i << "\n";

    return 0;
}
Developer technologies | C++
{count} votes

Accepted answer
  1. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2022-05-16T07:57:02.503+00:00

    Hi @Frederic Reinhardt ,

    Tried setting the Code Page to UTF-8 and I got the following results:

    202197-code.png

    202170-2019.png

    Best regards,

    Elya

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Frederic Reinhardt 21 Reputation points
    2022-05-16T09:41:09.453+00:00

    Thank you! That worked. I have now also figured out that one can change the encoding in the "save as"-dialogue by clicking on the little arrow besides "Speichern" (in the german version).

    I think Visual Studio automatically chose different encodings for the two files when i generate a new project. It chose UTF-8 for the main source file, because it was generated with german comments containing Umlaute like "ü", while it chooses ANSI encoding for the other files.

    202247-image.png


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.