Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to ALWAYS cast variables in C?

I'm writing some C code and use the Windows API. I was wondering if it was in any way good practice to cast the types that are obviously the same, but have a different name? For example, when passing a TCHAR * to strcmp(), which expects a const char *. Should I do, assuming I want to write strict and in every way correct C, strcmp((const char *)my_tchar_string, "foo")?

like image 219
Hoffa Avatar asked Jan 28 '26 06:01

Hoffa


2 Answers

Don't. But also don't use strcmp() but rather _tcscmp() (or even the safe alternatives).

_tcs* denotes a whole set of C runtime (string) functions that will behave correctly depending on how TCHAR gets translated by the preprocessor.

Concerning safe alternatives, look up functions with a trailing _s and otherwise named as the classic string functions from the C runtime. There is another set of functions that returns HRESULT, but it is not as compatible with the C runtime.

like image 59
0xC0000022L Avatar answered Jan 30 '26 21:01

0xC0000022L


No, casting that away is not safe because TCHAR is not always equal to char. Instead of casting, you should pick a function that works with a TCHAR. See http://msdn.microsoft.com/en-us/library/e0z9k731(v=vs.71).aspx

like image 39
Michael Price Avatar answered Jan 30 '26 19:01

Michael Price