Type Inference

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

Type Inference

-------------------------------------------------------
Type Inference refers to automatic deduction of the data type of an expression in a
programming language. In c++, this features is introduced in C++ 11. Before
introducing this features, We need to declare the data type of an expression
explicitly. But, after this feature data type of an expression deducted
automatically due to this feature the time of compilation increases slightly but it
does not affect the run time of the program.

1) auto keyword => 'auto' keyword is used to deduct the data type of variable
automatically from its being intializer. In case of function, if the return type of
function is auto then that will be evaluated by return type expression at runtime.

NOTE - If variable is declared with auto keyword then it should be initialize at


the time of its declaration otherwise we will get error.

example -
#include <iostream>
#include <typeinfo>

using namespace std;

int main() {
// auto x;
// x = 12;
// above statement we will get error. because, if variable is declared with
auto then is must be initialize at the time of declaration.
// otherwise we will get error.

auto x = 11;
auto f = 3.14;
auto c = 's';
auto s = "subodh";

cout << endl << "type of x : " << typeid(x).name();


cout << endl << "type of f : " << typeid(f).name();
cout << endl << "type of c : " << typeid(c).name();
cout << endl << "type of s : " << typeid(s).name();

return EXIT_SUCCESS;
}
output =>
type of x : i
type of f : d
type of c : c
type of s : PKc

You might also like