Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use _T or _TEXT on C++ string literals?

For example:

// This will become either SomeMethodA or SomeMethodW, // depending on whether _UNICODE is defined. SomeMethod( _T( "My String Literal" ) );  // Becomes either AnotherMethodA or AnotherMethodW. AnotherMethod( _TEXT( "My Text" ) ); 

I've seen both. _T seems to be for brevity and _TEXT for clarity. Is this merely a subjective programmer preference or is it more technical than that? For instance, if I use one over the other, will my code not compile against a particular system or some older version of a header file?

like image 410
Joe Avatar asked Jan 15 '10 20:01

Joe


People also ask

Can you use strcmp with a string literal?

yes it is perfectly safe and considered standard practice. String literals are guaranteed to be properly null terminated.

What characters must enclose a string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

Can we modify string literal in C?

The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.

Are literals Lvalues?

A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are rvalues.


1 Answers

A simple grep of the SDK shows us that the answer is that it doesn't matter—they are the same. They both turn into __T(x).

 C:\...\Visual Studio 8\VC>findstr /spin /c:"#define _T(" *.h  crt\src\tchar.h:2439:#define _T(x)       __T(x)  include\tchar.h:2390:#define _T(x)       __T(x)  C:\...\Visual Studio 8\VC>findstr /spin /c:"#define _TEXT(" *.h  crt\src\tchar.h:2440:#define _TEXT(x)    __T(x)  include\tchar.h:2391:#define _TEXT(x)    __T(x) 

And for completeness:

 C:\...\Visual Studio 8\VC>findstr /spin /c:"#define __T(" *.h  crt\src\tchar.h:210:#define __T(x)     L ## x  crt\src\tchar.h:889:#define __T(x)      x  include\tchar.h:210:#define __T(x)     L ## x  include\tchar.h:858:#define __T(x)      x 

However, technically, for C++ you should be using TEXT() instead of _TEXT(), but it (eventually) expands to the same thing too.

like image 177
i_am_jorf Avatar answered Sep 18 '22 07:09

i_am_jorf