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

uninitialized local variable used c++

Why can’t I initialize the integer variable num with the value of the number field of the Strct structure?

#include <iostream>

struct Strct
{
    float number = 16.0f;
};

int main()
{
    Strct* strct;
    int num = strct->number;
    return 0;
}

Error List: C4700 uninitialized local variable 'strct' used

>Solution :

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

Why can’t I initialize the integer variable num with the value of the number field of the Strct structure?

Because the pointer is uninitialised, and thus it doesn’t point to any object. Indirecting through the pointer, or even reading the value of the pointer result in undefined behaviour.

I thought my strct points to the Strct structure, that is, to its type

No. Pointers don’t point to types. Object pointers point to objects. Types are not objects in C++.

16.0f is not the value of number. 16.0f is the default member initialiser of that member. If you create an object of type Strct, and you don’t provide an initialiser for that member, then the default member initialiser will be used to initialise the member of the object in question.

then can I define a member function that returns the address of this structure?

A structure is a type. A type isn’t stored in an address. There is no such thing as "address of a type".


Here is an example of how to create a variable that names an instance of the class Strct:

Strct strct;

You can access the member of this variable using the member access operator:

int num = strct.number;

Here is an example of how to create an instance that doesn’t use the default member initialiser:

Strct strct = {
    .number = 4.2f,
};
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