NeoPhoenix
NeoPhoenix

Reputation: 41

C++ struct initialization assertion fails

#include <cassert>
#include <string>
struct AStruct 
{ 
    int x; 
    char* y; 
    int z; 
};
int main()
{ 
    AStruct structu = {4, "Hello World"};
    assert(structu.z == ???);
}

What should I write in place of ??? to have a successful assertion?
I used assert(structu.z == 0); but unfortunately got the error
int main(): Assertion 'structu.z == 0 failed.Aborted'

Upvotes: 3

Views: 1305

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

By "successful", I'm assuming you mean one that doesn't create an error message. You probably want:

assert(structu.z == 0);

Note that I'm using ==, and not =.

This assertion should never trigger, because with the code given, structu.z is guaranteed to be equal to 0.

Upvotes: 3

user2100815
user2100815

Reputation:

You want:

 assert(structu.z == 0);

Your code assigns to the z member instead of testing it. And if you did get the message your edited question says you did, your compiler is broken. Which one is it?

Upvotes: 5

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

assert(structu.z == 0) should work because the member z would be value initialized.

Upvotes: 3

Related Questions