James Allan
James Allan

Reputation: 313

String literals in C++ with _T macro

What is the difference (if any) between this

_T("a string")

and

_T('a string')

?

Upvotes: 1

Views: 870

Answers (5)

Steve Jessop
Steve Jessop

Reputation: 279455

'a string' is a so-called "multicharacter literal". It has type int, and an implementation-defined value. This is [lex.ccon] in the standard.

I don't know what values MSVC gives to multicharacter literals, and I don't know for sure what the MS-specific _T macro ends up doing with it, but I expect you get a narrow multicharacter literal on narrow builds, and a wide multicharacter literal on wide builds. The prefix L is the same for strings and character literals.

It's wrong, anyway: multicharacter literals are pretty much useless and certainly are no substitute for strings. "a string" is a string literal, which is what you want.

Upvotes: 3

LihO
LihO

Reputation: 42133

You use '' for single character and "" for strings. _T('a string') is wrong and its behaviour is compiler-specific.

In case of MSVC it uses first character only. Example:

#include <iostream>
#include <tchar.h>

int main()
{
    if (_T('a string') == _T('a'))
        std::cout << (int)'a' << " = " << _T('a');
}

output: 97 = 97

Upvotes: 2

Tobi Wei&#223;haar
Tobi Wei&#223;haar

Reputation: 1677

Single quotations are primarily used when denoting a single character:

char c = 'e' ;

Double quotations are used with strings and output statements:

string s = "This is a string";
cout << "Output where double quotations are used.";

Upvotes: 1

Borealid
Borealid

Reputation: 98559

First, _T isn't a standard part of C++. I've added the "windows" tag to your question.

Now, the difference between these is that the first is correct and the second is not. In C++, ' is for quoting single characters, and " is for quoting strings.

Upvotes: 4

Lefteris
Lefteris

Reputation: 3256

The second is wrong. You are placing a string literal in between single quotes.

Upvotes: 3

Related Questions