473,569 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"memset" vs "= {0}"...Are they equivalent if your initializing variables?

Say you have a struct:

struct MYSTRUCT
{
int x;
int y;
int w;
int h;
};

and you want to declare an instance of that struct and initialize it
to zero. Is "memset" necessary or can i simply initially set it equal
to {0}.

Is this:
MYSTRUCT myStruct = {0};

the same as this:
MYSTRUCT myStruct;
memset(&myStruc t, 0, sizeof(MYSTRUCT ));

?

The first way seems faster, but I see alot of people doing it the
second way. Could someone please shed some light on the subject?
TIA.
Jul 22 '05 #1
17 19853

<No****@runtime .com> wrote in message
news:fq******** *************** *********@4ax.c om...
Say you have a struct:

struct MYSTRUCT
{
int x;
int y;
int w;
int h;
};

and you want to declare an instance of that struct and initialize it
to zero. Is "memset" necessary or can i simply initially set it equal
to {0}.

Is this:
MYSTRUCT myStruct = {0};

the same as this:
MYSTRUCT myStruct;
memset(&myStruc t, 0, sizeof(MYSTRUCT ));

?

The first way seems faster,
Why do you say it 'seems faster'? The only way to tell if it is faster is to
time it (or if you are very knowledgable look at the generated machine
code). Remeber compilers are usually pretty code at optimising code, I would
certainly hope that the two methods would be exactly the same on a good
compiler (but I haven't actually checked this).
but I see alot of people doing it the
second way. Could someone please shed some light on the subject?
The two ways are the same for the struct you have declared. But if you had a
struct with members that had a constructor (e.g. a std::string) then memset
would be wrong. So that is the advantage of the second method, it works in
more situations and you could reasonable hope to get a compiler error
message if you used it incorrectly.
TIA.


john
Jul 22 '05 #2
On Wed, 22 Sep 2004 03:17:47 -0500, No****@runtime. com wrote:
Say you have a struct:

struct MYSTRUCT
{
int x;
int y;
int w;
int h;
};

and you want to declare an instance of that struct and initialize it
to zero. Is "memset" necessary or can i simply initially set it equal
to {0}.

Is this:
MYSTRUCT myStruct = {0};

the same as this:
MYSTRUCT myStruct;
memset(&myStru ct, 0, sizeof(MYSTRUCT ));

?

The first way seems faster, but I see alot of people doing it the
second way. Could someone please shed some light on the subject?


The first way is generally better, since it zero initializes all
members. Memsetting to 0 is not always the same as zero initializing,
particularly for floating point and pointer members, which may have 0
values that aren't all bits zero.

Performance wise, I don't know which would be faster, you'd have to
measure it.

Tom
Jul 22 '05 #3
> would be wrong. So that is the advantage of the second method, it works in

I meant first method.

john
Jul 22 '05 #4
> struct MYSTRUCT
{
int x;
int y;
int w;
int h;
};
MYSTRUCT myStruct = {0};
All this does is set "myStruct.x " to 0, all the others
still contain no particular value.

MYSTRUCT myStruct;
memset(&myStruc t, 0, sizeof(MYSTRUCT ));


This is the Microsoft way of doing things.

In fact, they've even made a... uh... macro... out of it
called "ZeroMemory " which you use like so:

ZeroMemory(&myS truct, sizeof(MYSTRUCT ));

Don't use the Microsoft way. It's non-portable, plus it
screws things up when you have the likes of:

struct Blah
{
int k;
std::string p;
};

Instead, do the following:

struct Blah
{
int x;
int y;
int w;
int h;
std::string r;
};

Blah poo = Blah();

This gives all member variables their default value, which
for the intrinsic types is 0, for pointer is the null
pointer value which may or may not be represented by 0
(memset is unaware of this and as such can screw things
up), and for classes it calls their default constructor
with no arguments.
Blah poo = Blah();

is superiour in every way and is fully portable. Use it!
-JKop
Jul 22 '05 #5

"JKop" <NU**@NULL.NULL > wrote in message news:1Z******** ***********@new s.indigo.ie...
All this does is set "myStruct.x " to 0, all the others
still contain no particular value.
Wrong answer....When you omit terms in an aggregate initializer the rest
are default initialized.

Instead, do the following:

struct Blah
{
int x;
int y;
int w;
int h;
std::string r;
};

Blah poo = Blah();

So would
Blah poo = { 0 };

Jul 22 '05 #6
On Wed, 22 Sep 2004 11:02:21 GMT, JKop <NU**@NULL.NULL > wrote:
struct MYSTRUCT
{
int x;
int y;
int w;
int h;
};

MYSTRUCT myStruct = {0};


All this does is set "myStruct.x " to 0, all the others
still contain no particular value.


Nope, remaining members are value-initialized, which for built-ins
means initialized to 0. You can also do:

MYSTRUCT myStruct = {};

to get the same effect.

Tom
Jul 22 '05 #7
> MYSTRUCT myStruct = {};
Cool! Didn't know that.

The only advantage

MYSTRUCT myStruct = MYSTRUCT();

would have over it thought is that it can be used for *any*
type, as opposed to just for arrays and POD's. My proposal
would be especially preferable for use in a template.

-JKop
Jul 22 '05 #8
On Wed, 22 Sep 2004 11:02:21 GMT, JKop <NU**@NULL.NULL > wrote:
struct Blah
{
int x;
int y;
int w;
int h;
std::string r;
};

Blah poo = Blah();

This gives all member variables their default value, which
for the intrinsic types is 0, for pointer is the null
pointer value which may or may not be represented by 0
(memset is unaware of this and as such can screw things
up), and for classes it calls their default constructor
with no arguments.
Blah poo = Blah();

is superiour in every way and is fully portable. Use it!
-JKop


Not necessarily. Of the three methods I've tested, Blah()
appears to be the slowest.

The method:

Blah poo;
memset(&poo, 0, sizeof(Blah));

is the fastest, and

Blah poo = {0}

is a very close second;

Basically, you must compromise speed for safety and portability.

This is first time I've ever timed functions. I'm Visual Studio.NET
2003, SDK, WindowsXP.

My timing algorithm:
LARGE_INTEGER start;
LARGE_INTEGER end;
QueryPerformanc eCounter( &start );
....Do Something
QueryPerformanc eCounter( &end );
TRACE( TEXT( "Time = %d\n" ), end.QuadPart-start.QuadPart );

Granted, we're talking minimal differences, but that's besides the
point.

Please explain a little deeper as to why memset might not set a
pointer or a floating point number to zero. It does on my computer.

-Nollie
Jul 22 '05 #9
> Not necessarily. Of the three methods I've tested, Blah()
appears to be the slowest.

The method:

Blah poo;
memset(&poo, 0, sizeof(Blah));

is the fastest, and

Blah poo = {0}

is a very close second;

Basically, you must compromise speed for safety and portability.

This is first time I've ever timed functions. I'm Visual Studio.NET
2003, SDK, WindowsXP.

My timing algorithm:
LARGE_INTEGER start;
LARGE_INTEGER end;
QueryPerformanc eCounter( &start );
...Do Something
QueryPerformanc eCounter( &end );
TRACE( TEXT( "Time = %d\n" ), end.QuadPart-start.QuadPart );

Granted, we're talking minimal differences, but that's besides the
point.

Please explain a little deeper as to why memset might not set a
pointer or a floating point number to zero. It does on my computer.

-Nollie


Sometimes it takes me 10mins 23secs to get to the bustop. Sometimes it takes
9mins 58secs...

I wouldn't use "QueryPerforman ceCounter" as an indicator for this, unless
you time it a few thousand times and get the average, but even still, I'm
not sure how accurate it'd be.

As regards pointers... well let's say that on a certain system, a pointer
variable takes up 32 bits in memory, as so:
0000 0000 0000 0000 0000 0000 0000 0000
What you're looking at above is "all bits zero". On Windows, this indicates
that the pointer is a null pointer. Now imagine a system where the memory
address 0 is a valid one, ie. it's the first byte of memory, and that on
this particular system, the null pointer value is:

1111 1111 1111 1111 1111 1111 1111 1111
When you write a program with the following line in it:
int* p_k = 0;

The compiler doesn't produce code that sets all bits to zero... no no...
what it does is produce code that sets it to the null pointer value for that
system (and/or for that type, I believe systems may choose to have different
null pointer values depending on the type...). But "memset" doesn't have a
clue about this, all it does is set all bits to zero, which may be a valid
memory address on some systems, hence it's not portable.

And as regards floating point numbers, implementations aren't obligated to
represent the value zero as "all bits zero" either.

I don't see how either of the three could be slower/faster than each other,
they should all yield the same machine code (except maybe the call to
"memeset" might add overhead if it's not inline...)
-JKop
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2507
by: J. Campbell | last post by:
From reading this forum, it is my understanding that C++ doesn't require the compiler to keep code that does not manifest itself in any way to the user. For example, in the following: { for(int i = 0; i < 10; ++i){ std::cout << i << std::endl; for(int j = 0; j < 0x7fffffff; ++j){} } }
8
3362
by: Chul Min Kim | last post by:
Hi, I got a BUS ERROR from one of my company's program. Let me briefly tell our environment. Machine : Sun E3500 (Ultra Sparc II 400Mhz CPU 4EA) OS : Solaris7 Compiler : Sun Workshop 5.0 cc complier I get "BUS ERROR" only when I execute the binary which builds
7
2077
by: adelfino | last post by:
I mean: unsigned char foo = ""; is the same as: unsigned char foo; memset (foo, '\0', bar); ?
77
3975
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from...
10
25124
by: steingold | last post by:
Hi all, I wrote an application that takes snapshots using the snapshot monitor API (db2gGetSnapshot and db2GetSnapshotSize), every now and then these methods fail and I get SQL1024N error (A database connection does not exist. SQLSTATE=08003). The application is attached to the db2 instance initialization, and to be on the safe side, I...
13
6857
by: bwaichu | last post by:
Now, I read the faq, and it suggests using sprintf. However, I want to all ways know where the integer finishes in the string. Basically, I want to: nbr | other data But the other data all ways has to start at the same place. I had some problems using sprintf to accomplish this requirement. Maybe I am overlooking something. But...
26
2163
by: Frederick Gotham | last post by:
I have a general idea of the different kinds of behaviour described by the C Standard, such as: (1) Well-defined behaviour: int a = 2, b = 3; int c = a + b; (Jist: The code will work perfectly.)
84
8522
by: aarklon | last post by:
Hi all, I found an interesting article here:- http://en.wikipedia.org/wiki/Criticism_of_the_C_programming_language well what do you guys think of this article....??? Is it constructive criticism that needs to be appreciated always...???
3
3404
by: Hank | last post by:
Steve Holden wrote: Hi, Steve, This not simply a pathological condition. My people are keeping trying many ways to have job done, and the memory problem became the focus we are paying attention on at this moment. Could you please give us some clear clues to obviously call python to free memory. We want to control its gc operation handily as...
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.