Differences between C# "var" and C++ "auto"

In C# var keyword works only locally inside function:

var i = 10; // implicitly typed 

In C++ auto keyword can deduce type not only in variables, but also in functions and templates:

auto i = 10;

auto foo() { //deduced to be int
    return 5;
}

template<typename T, typename U>
auto add(T t, U u) {
    return t + u;
}

From performance point of view, auto keyword in C++ does not affect runtime performance. And var keyword does not affect runtime performance as well.

Another difference can be in intellisense support in IDE. Var keyword in C# can be easily deduced and you will see the type with mouse over. With auto keyword in C++ it might be more complicated, it depends on IDE.


To put things simply, auto is a much more complicated beast than var.

First, auto may only be part of the deduced type; for example:

std::vector<X> xs;
// Fill xs
for (auto x : xs) x.modify(); // modifies the local copy of object contained in xs
for (auto& x : xs) x.modify(); // modifies the object contained in xs
for (auto const& x : xs) x.modify(); // Error: x is const ref

Second, auto may be used to declare multiple objects at once:

int f();
int* g();
auto i = f(), *pi = g();

Third, auto is used as part of the trailing return type syntax in function declarations:

template <class T, class U>
auto add(T t, U u) -> decltype(t + u);

It may also be used for type deduction in function definitions:

template <class T, class U>
auto add(T t, U u) { return t + u; }

Fourth, in the future it may start to be used to declare function templates:

void f(auto (auto::*mf)(auto));
// Same as:
template<typename T, typename U, typename V> void f(T (U::*mf)(V));

They are equivalent. They both allow you not to specify the type of a variable yourself, but the variable stays strongly-typed. The following lines are equivalent in c#:

var i = 10; // implicitly typed  
int i = 10; //explicitly typed  

And the following lines are equivalent in c++:

auto i = 10;
int i = 10;

However, you should keep in mind that in c++ the correct type of an auto variable is determined using the rules of template argument deduction for a function call.

Tags:

C#

C++

Var

Auto