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:
redefinition of 'test' with a different type
Is it possible to assign a new type to a variable somehow?
CodePudding user response:
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;
}
CodePudding user response:
In C 17 and newer, std::variant
is a type that can be used to store multiple different types of data. Though you'll have to do a bit of finagling with visitors to get the polymorphic print
you know from Python.
#include <variant>
#include <string>
#include <iostream>
struct PrintVisitor {
template <typename T>
void operator()(const T& arg) {
std::cout << arg << std::endl;
}
};
int main() {
std::variant<std::string, int> test = "hello world";
std::visit(PrintVisitor(), test);
test = 5;
std::visit(PrintVisitor(), test);
}