NO

Author Topic: sizeof operator  (Read 1696 times)

Offline John Z

  • Member
  • *
  • Posts: 840
sizeof operator
« on: August 08, 2024, 11:56:15 PM »
So wondering -

if
LVCOLUMNW TableCol;       // Make Column struct

then is it better to use
memset(&TableCol, 0, sizeof(TableCol));   // Reset Column

or
memset(&TableCol, 0, sizeof(LVCOLUMNW));   // Reset Column

or
Both are OK to use w/o distinction

?

John Z

Offline MrBcx

  • Global Moderator
  • Member
  • *****
  • Posts: 186
    • Bcx Basic to C/C++ Translator
Re: sizeof operator
« Reply #1 on: August 09, 2024, 04:00:30 AM »
ChatGPT says this and I agree.

Both options are technically correct and will have the same effect since sizeof(TableCol) and sizeof(LVCOLUMNW) are equivalent.

However, using sizeof(TableCol) is generally preferred because it directly ties the memset operation to the actual variable you're working with. This approach improves code maintainability. If the type of TableCol ever changes, the code will still work correctly without needing to update the memset call.

So, while both are okay, using sizeof(TableCol) is often considered better practice.
Bcx Basic to C/C++ Translator
https://www.BcxBasicCoders.com

Offline John Z

  • Member
  • *
  • Posts: 840
Re: sizeof operator
« Reply #2 on: August 09, 2024, 04:05:40 AM »
Great - Thanks MrBcx!

I was using TableCol but thought I'd ask to be sure.

Appreciate it!

John Z

Offline WiiLF23

  • Member
  • *
  • Posts: 85
Re: sizeof operator
« Reply #3 on: August 17, 2024, 06:27:33 AM »
I always use this when initializing LVITEMW struct

Code: [Select]
LVITEMW lvItemFileName;
memset(&lvItemFileName, 0, sizeof(LVITEMW));
...

You can use memset() or LVITEMW lvItemFileName = { 0 }. I prefer memset().

Offline MrBcx

  • Global Moderator
  • Member
  • *****
  • Posts: 186
    • Bcx Basic to C/C++ Translator
Re: sizeof operator
« Reply #4 on: August 17, 2024, 04:44:34 PM »
I always use this when initializing LVITEMW struct

Code: [Select]
LVITEMW lvItemFileName;
memset(&lvItemFileName, 0, sizeof(LVITEMW));
...

You can use memset() or LVITEMW lvItemFileName = { 0 }. I prefer memset().

For simple datatypes (ints, floats, etc), ={0}; works great.

For user-defined types, some compilers may issue warnings, in which case we can explicitly
zero each member using, for example, this approach:     struct MyStruct mstr = { 0, 0, 0.0, 0.0 };
Bcx Basic to C/C++ Translator
https://www.BcxBasicCoders.com

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2097
Re: sizeof operator
« Reply #5 on: August 17, 2024, 11:15:04 PM »
Code: [Select]
={0};optimizer can generate smaller code, so useful in small code  ;)
May the source be with you