devjeetroy
devjeetroy

Reputation: 1945

Regarding passing strings to win32 api functions

I was wondering if there is any advantage (for shorter strings only) of using a string datatype instead of a char array, or simply the string such as:

TextOut(hDC, 10, 10, "Hello", sizeof("HEllO") - 1)

Upvotes: 2

Views: 673

Answers (2)

Scigrapher
Scigrapher

Reputation: 2116

One difference between a string datatype and the inline string as you've used them above is that using a separate named reference (whether the type is a string or char array) prevents the common bug where you change the string but forget to change the copy inside the sizeof(). If the new string is a different length, it will have undesired consequences. Having a single place that allows you to update both simultaneously, whether via a const char* or string datatype, is a better practice.

const TCHAR TEXTOUT_TEXT[] = _T("Hello");
TextOut( hDC, 10, 10, TEXTOUT_TEXT, sizeof(TEXTOUT_TEXT) / sizeof(TEXTOUT_TEXT[0]) - 1 );

Upvotes: 1

Will Chesterfield
Will Chesterfield

Reputation: 1780

In practice, this doesn't matter at all.

That said, the Win32 APIs require LPSTRs or LPWSTRs, so anything which is not "one of those" will first have to be converted into the appropriate char* type, so a very tiny bit of extra work is required.

I'd say the vastly bigger consideration is using a datatype which is convenient/familiar/easy for you to work with.

Upvotes: 1

Related Questions