Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Incrementing a size_t default value giving garbage value?

Why does Incrementing a size_t default value giving garbage value?

#include <iostream>

using namespace std;

struct Test {
  size_t a;
  size_t b;
};

int main() {
  Test wrong;
  cout << (wrong.a) ++;
  cout << endl;
  cout << (wrong.b) ++;

  cout << endl;

  Test right {};
  cout << (right.a) ++;
  cout << endl;
  cout << (right.b) ++;

  return 0;
}

For the above code getting output

Output:

93937114642880
93937114642304
0
0

Is this because size_t not a POD? Also why does the Test wrong; not calling the default constructor and initialises the fields to default values?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Why does Incrementing a size_t default value giving garbage value?

You need to be very careful with your terminology. default has specific meaning in C++.

In your first case, the size_t variables in wrong are NOT being given default values. You are incrementing uninitialized variables that have indeterminate values. This is undefined behavior. So, you get garbage output because you are acting on garbage values to begin with.

In your second case, you are value-initializing the size_t variables in right to 0 before then incrementing them, which is well-defined behavior. And since you are using the post-increment ++ operator, which returns the previous value before it is incremented, that is why the output is 0 rather than 1.

Is this because size_t not a POD?

No. size_t is a POD type.

Also why does the Test wrong; not calling the default constructor and initialises the fields to default values?

Test wrong; performs default initialization. It does call the default constructor, but you simply didn’t implement that constructor yourself, so the compiler auto-generates one for you. And since all of the members are PODs, there is nothing for the generated constructor to do, so it doesn’t initialize the members at all.

Test right{}; performs value initialization, which in this case will zero out the size_t members.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading