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;
}
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,527 questions
{count} votes

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