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"?
Conclusion. In a nutshell, the main difference between C and C++ is that C is a procedural with no support for objects and classes whereas C++ is a combination of procedural and object-oriented programming languages.
C++ is a superset of C, so both languages have similar syntax, code structure, and compilation. Almost all of C's keywords and operators are used in C++ and do the same thing. C and C++ both use the top-down execution flow and allow procedural and functional programming.
Compared to C++, C is the simpler and ultimately faster programming language. C is procedural and does not support classes and objects, meaning it has less functionality than C++. This allows you to spend more time focusing on what you can do with C's libraries, especially at the OS level.
Let's continue with a discussion of all the five different standards of C — K&R C, ANSI C, C99, C11 and Embedded C. For the purposes of our discussion, the compiler used is the gcc C compiler from the GNU Compiler Collection (GCC).
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With