C++ Crash Course: a fast-Paced Introduction



Yüklə 7 Mb.
Pdf görüntüsü
səhifə29/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   25   26   27   28   29   30   31   32   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

auto Initialization
C often requires you to repeat type information more than once. In C++, 
you can express a variable’s type information just once by utilizing the 
auto
keyword. The compiler will know the variable’s type because it knows the 
type of the value being used to initialize the variable. Consider the follow-
ing C++ variable initializations:
int x = 42;
auto y = 42;
Here, 
x
and 
y
are both of 
int
type. You might be surprised to know that 
the compiler can deduce the type of 
y
, but consider that 42 is an integer 
literal. With 
auto
, the compiler deduces the type on the right side of the 
equal sign 
=
and sets the variable’s type to the same. Because an integer 
literal is of 
int
type, in this example the compiler deduces that the type of 
y
is also an 
int
. This doesn’t seem like much of a benefit in such a simple 
example, but consider initializing a variable with a function’s return value
as Listing 10 illustrates.
#include
struct HolmesIV {
--
snip
--
};


An Overture to C Programmers
xliii
HolmesIV* make_mike(int sense_of_humor) {
--
snip
--
}
int main() {
auto mike = make_mike(1000);
free(mike);
}
Listing 10: A toy program initializing a variable with the return value of a function 
The 
auto
keyword is easier to read and is more amenable to code refac-
toring than explicitly declaring a variable’s type. If you use 
auto
freely while 
declaring a function, there will be less work to do later if you need to change 
the return type of 
make_mike
. The case for 
auto
strengthens with more complex 
types, such as those involved with the template-laden code of the stdlib. The 
auto
keyword makes the compiler do all the work of type deduction for you.
N O T E
 
You can also add 
const

volatile

&
, and 
*
 qualifiers to 
auto


Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   25   26   27   28   29   30   31   32   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin