Author Topic: C/C++ pitfalls  (Read 3581 times)

Patrice Terrier

  • Administrator
  • *****
  • Posts: 1983
    • zapsolution
C/C++ pitfalls
« on: July 18, 2020, 01:39:06 pm »
When moving from another programming language to c/C++,
here are some common pitfalls you must be warned about:

ALWAYS initialize your variables and structures,
because they are just pointing to a memory location, without first cleaning the matching allocated memory area.
The memset API allows you to fill the allocated memory with a specific character (use 0 as default value).
Or use the C++ = { 0 } short cut, to fill with nulls.

When writing DLL for 32-bit,
code generation: /Gz uses the _stdcall calling convention. (x86 only)
And always create a define module (.def extension) with the list of exported functions.
Then go to Project > Properties > Linker > Input > Module Definition File and enter the name of the DEF file.

Don't confuse = and ==,
This is one of the most common error when translating from another language to C/C++, and very hard to detect.
= is for affectation
== is to check equality

String comparison,
Never use = or == to perform string comparison, but int nCompare =_wcsicmp(string1, string2)
The nCompare value indicates the relation of string1 to string2 as follows:
< 0 string1 less than string2
0 string1 identical to string2
> 0 string1 greater than string2

Avoid long/int divide rounding errors,
(float) single = long1 / long2 (that is a NoNo)
(float) single = long1 / (float) long2 (that is good)

« Last Edit: March 23, 2022, 10:06:24 am by Patrice Terrier »
(Always working with the latest Windows version available...)