-3

I am getting error like

/hackerearth/CPP14_28/s_e3.cpp: In function ‘int main()’: /hackerearth/CPP14_28/s_e3.cpp:6:10: error: declaration of ‘auto x’ has no initializer auto x; ^ 

My code is ,

#include <iostream>
using namespace std;

int main()
{
    auto x;
    cin >> x;
    cout << x;
    return 0;
}

I want similar functionality that data type should be dynamically assigned

Kamesh S
  • 143
  • 2
  • 8
  • 1
    You can't do that. Types are determined at compile time in C++. – Mat Mar 30 '18 at 17:58
  • I hope it is possible in c++14 https://preshing.com/20141202/cpp-has-become-more-pythonic/ . But i count not find the way t do it – Kamesh S Mar 30 '18 at 18:05
  • 1
    You can not use 'auto x;' you need to use according to reference [http://en.cppreference.com/w/cpp/language/auto] – amalbala Mar 30 '18 at 18:08
  • how to do it ?? – Kamesh S Mar 30 '18 at 18:19
  • `auto` doesn't work that way. You could maybe take input as a string and then make some tests to determine what you can convert it to. – Fred Larson Mar 30 '18 at 18:22
  • 1
    `auto` determines the type of the variable based on what you initialize it with. No initialization, no type. `auto x = 0;`, x is an `int`. `auto x = 0.0;`, `x` is a `double`. `auto x = Chainsaw()`, `x` is a `Chainsaw`. – user4581301 Mar 30 '18 at 18:46

2 Answers2

3

You're misusing the auto keyword. The type that actually gets used is determined by the value used to initialize the variable at compile time. It has nothing to do with the ability to determine the type of variable to use at runtime.

For example, if you write auto x = 0, the compiler sees that you're initializing the variable with an int and pretty much compiles it as if it was int x = 0.

Depending on what you're trying to do, you might want to take the input as a string and parse it later, or somehow determine what type of input it is before reading the value.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
0

Objects declared with auto typing need to copy their static type from their initializers; What your 'x' is missing. C++ - just like C - is a statically typed language. Extra string processing is needed to decode the input string value. If the set of possible types is limited to a known countable set, a proper std::variant could be used to hold the value.

Red.Wave
  • 2,790
  • 11
  • 17
  • "Unfortunately, C++ - just like C - is a statically typed language" - I disagree strongly with that. In my opinion it is a *Very good* thing that C++ is statically typed. Dynamically typed languages may *seem* convenient, but all too often open the door to tricky type related errors at runtime. – Jesper Juhl Mar 30 '18 at 19:10
  • No disagreements. Just sympathy with the OP. – Red.Wave Mar 30 '18 at 20:21
  • 1
    IMHO answers need to be purely factual. Sympathy and the like has no place there. Just facts. – Jesper Juhl Mar 30 '18 at 20:23
  • That word, I just removed. – Red.Wave Mar 30 '18 at 20:26