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

Kangjun Heo picture Kangjun Heo · Nov 24, 2016 · Viewed 15.7k times · Source

I'm learning C++ now because I need to write some low level programs.

When I learned about "auto" keyword, it reminds me "var" keyword, from C#.

So, what are differences of C# "var" and C++ "auto"?

Answer

Tomas Kubes picture Tomas Kubes · Nov 24, 2016

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.