c++variables

Declaring a variable without specifying its data type in C++


Why is it necessary to specify the datatype of a variable? What if my program requires the user to enter data that could belong to any one of two non intersecting data types? Shouldn't the option of declaring a variable without specifying a variable be provided so as to account for a situation. Why can't we let the computer decide the data type on the basis of user input? If the compiler has enough capability to identify a type error, I'm sure it can easily specify a data type on the basis of the input.


Solution

  • Compilers don't deal with input, so that's no option.

    There's boost::variant<T,U> which is a type can hold either T or U values, but you still have to specify to the compiler all possible options, and you have to make clear what you put in.

    User input always starts out as a string. Parsing turns that into types, but the result depends on the actual parsing. If you're parsing float values, 0 is a perfectly fine float value.