4

According to the answers in this question, a literal like L"test" has type wchar_t[5]. But the following code with GCC seems to say something different:

int main()
{
    struct Test{char x;} s;
    s="Test"; // ok, char* as expected
    s=L"Test"; // ??? I'd expect wchar_t*
    return 0;
}

Here's how I compile it (gcc 5.2, but same results are with 4.5 and 4.8):

$ gcc test.c -o test -std=c99
test.c: In function ‘main’:
test.c:4:6: error: incompatible types when assigning to type ‘struct Test’ from type ‘char *’
     s="Test"; // ok, char* as expected
      ^
test.c:5:6: error: incompatible types when assigning to type ‘struct Test’ from type ‘long int *’
     s=L"Test"; // ??? I'd expect wchar_t*
      ^

Apparently, instead of the expected array of wchar_t I get array of long int. What's wrong here?

Community
  • 1
  • 1
Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • 5
    But on Linux wchar_t is 32 bit, in some architectures it may even be just a typedef for long int. – Adriano Repetti Aug 28 '16 at 07:37
  • 1
    `struct Test{} s;` doesn't make sense. Structs must have at least one member. Please present code that compiles. – 2501 Aug 28 '16 at 07:44
  • 1
    `wchar_t` is not a built-in type. It is an implementation defined type, that happens to be equivalent to a `long int` on your system. On my system, it's just a plain old `int`. – user3386109 Aug 28 '16 at 07:45
  • 3
    @2501 if I presented the code which compiles, I'd never find out the type of the literal. It's intentionally crafted to give a meaningful error. – Ruslan Aug 28 '16 at 07:48
  • 2
    On my windows I get `...assigning to type 'struct Test' from type 'short unsigned int *'` – Support Ukraine Aug 28 '16 at 07:48

1 Answers1

2

The type wchar_t is not a fundamental type, like char. It is an implementation-defined synonym of an integer type1.


1 (Quoted from: ISO/IEC 9899:201x 7.19 Common definitions 2.)
wchar_t which is an integer type whose range of values can represent distinct codes for all members of the largest extended character set specified among the supported locales;

2501
  • 25,460
  • 4
  • 47
  • 87