How to Create a variable without assigning the value, and assign the value later in C++ ?


In C++, you can create a variable without assigning a value to it by simply declaring it without an initializer. You can then assign a value to the variable later using the assignment operator (=).

Here's an example:

#include <iostream>

int main() {
    int myVariable; // declare variable without assigning a value
    std::cout << "myVariable = " << myVariable << std::endl; // output the value of myVariable (which is undefined)

    myVariable = 42; // assign a value to myVariable
    std::cout << "myVariable = " << myVariable << std::endl; // output the new value of myVariable

    return 0;
}

Output:

myVariable = -858993460
myVariable = 42

In the above example, we declare an integer variable myVariable without assigning a value to it. When we output the value of myVariable, it gives us an undefined value (in this case, -858993460). We then assign a value of 42 to myVariable and output the new value, which is 42.

Another way to create a variable without assigning a value is to use the default constructor of a class. For example, if you have a class MyClass with a default constructor, you can create an object of that class without assigning a value to it like this:

#include <iostream>

class MyClass {
public:
    MyClass() {} // default constructor
};

int main() {
    MyClass myObject; // create object without assigning a value
    std::cout << "myObject created" << std::endl;

    return 0;
}

Output:

myObject created

In this example, we create an object myObject of class MyClass without assigning a value to it. We then output a message to indicate that the object has been created.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.