-4

Is it possible to change the way of declaring variables and for it to accept any type of variable with c++ so something like this:

int main()
{
declare x = "Hello World!"
declare y = 1.2
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • `#define variable 5` – no ai please Jul 24 '21 at 20:33
  • 2
    `auto x = "Hello World!";` is legal; however what type is `x` and what can you do with it ? If you don't know the type of a variable it can hard to know how you can manipulate it. – Richard Critten Jul 24 '21 at 20:38
  • 1
    If you follow a [decent book](https://stackoverflow.com/q/388242/817643) from the last decade, it should cover it. What does your book say? – StoryTeller - Unslander Monica Jul 24 '21 at 20:39
  • The answer is yes you can do this with `auto` but its not a good idea to abuse this as it makes code less readable. People who have to read your code (including yourself in 6 months) will be unhappy with your decision to do this. – drescherjm Jul 24 '21 at 20:48

2 Answers2

4

With C++11 and newer, you can use auto. See https://en.cppreference.com/w/cpp/language/auto for more info.

With C++17 and newer, you can use std::any. This is more useful if you are loading a std::vector with arbitrary data.

However, in my experience as a software engineer, too much auto/any usage can lead to unclear code.

  • auto works great, is there any way to rename it so instead of auto it says define or something like that? – Joakim Hjalmarsson Jul 24 '21 at 21:48
  • @JoakimHjalmarsson Why would you want to do that? – Kyle Jul 24 '21 at 22:03
  • @JoakimHjalmarsson, I dont believe you can. ```auto``` is a keyword that directs the compiler to deduce the type. Because its not actually a type itself, you can't use ```using```. Trying to do something like ```#define auto define;``` probably wont work for the same reason. Also... why not just use auto? Or better yet, define your type? – WutsSoftware Jul 24 '21 at 22:08
1

I think you are looking for the auto keyword

Sebeke
  • 69
  • 4