question about variable-argument lists

  • Thread starter Thread starter Tao
  • Start date Start date
T

Tao

wstring StringFormat(wstring str0, ...)

{

wstring result = str0;

va_list list;

va_start(list, str0);

int i=0;

for(;;)

{

wchar_t* p=va_arg(list, wchar_t*);

if(p==0)

break;

wstring pattern;

pattern = L"{" + string_streaming::to_wstring(i) + L"}";

//Replace(result, pattern.c_str(), p);

i++;

}

va_end(list);

return result;

}



main()

{

StringFormat("A", "B");

}



The for loop should stop after 1 iteration, but it keeps running and the
wchar_t* p is set to some strange values.



thanks.
 
wstring StringFormat(wstring str0, ...)

{

wstring result = str0;

va_list list;

va_start(list, str0);

int i=0;

for(;;)

{

wchar_t* p=va_arg(list, wchar_t*);

if(p==0)

break;

wstring pattern;

pattern = L"{" + string_streaming::to_wstring(i) + L"}";

//Replace(result, pattern.c_str(), p);

i++;

}

va_end(list);

return result;

}



main()

{

StringFormat("A", "B");

}



The for loop should stop after 1 iteration, but it keeps running and the
wchar_t* p is set to some strange values.

You need to write:

StringFormat(L"A", L"B", (wchar_t*) 0);

It's important to cast 0 used as a pointer in variable argument lists,
particularly on 64-bit Windows, where sizeof(int) == 4 and sizeof(pointer)
== 8. I'm not sure how 64-bit compilers define NULL; perhaps they widen
this integer value to 64 bits, but I'd do the cast anyway. It helps a
little with self-documentation, and you'll be covered if you ever use a
compiler that has a different representation for integer zero and null
pointer values.
 
Back
Top