Search code examples
c#c++varauto

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


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

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

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


Solution

  • 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 a mouse over. With auto keyword in C++ it might be more complicated, it depends on IDE and tooling.