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

Changing variable in c++

I started learning C++ and I made a simple thing like printing variables etc, but I wanted to make a new value on a variable like in Python:

test = "hello world"
print(test)
test = 5
print(test + 6)

So I had this:

string test = "hello world";
cout << test << "\n";

And now I wanted to assign a number to test, so I used int test = 5;, but I got an error:

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

redefinition of ‘test’ with a different type

Is it possible to assign a new type to a variable somehow?

>Solution :

is it possible to assign a new type to a variable somehow?

A new type, no. C++ is a statically typed language. Variable types are specified at compile-time and cannot change at runtime.

For what you are asking, the closest thing available is std::variant in C++17 and later, which is a fixed class type that can hold different kinds of values at runtime, eg:

#include <iostream>
#include <string>
#include <variant>

using myVariant = std::variant<int, std::string>;

void print(const myVariant &v)
{
    std::visit([](const auto &x) { std::cout << x; }, v);
    std::cout << "\n";
}

int main()
{
    myVariant test;
    test = "hello world";
    print(test);
    test = 5;
    print(test);
    return 0;
}

Online Demo

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