Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:
The first one, known as c-like initialization, is done by appending an equal sign followed by the value to which the variable will be initialized:type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:
|
|
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()
): type identifier (initial_value) ;
For example:
|
|
Both ways of initializing variables are valid and equivalent in C++.
|
|
6 |
Introduction to strings
Variables that can store non-numerical values that are longer than one single character are known as strings.
The C++ language library provides support for strings through the standard string
class. This is not a fundamental type, but it behaves in a similar way as fundamental types do in its most basic usage.
A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we need to include an additional header file in our source code: <string>
and have access to the std
namespace (which we already had in all our previous programs thanks to the using namespace
statement).
|
|
This is a string |
As you may see in the previous example, strings can be initialized with any valid string literal just like numerical type variables can be initialized to any valid numerical literal. Both initialization formats are valid with strings:
|
|
Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and being assigned values during execution:
|
|
This is the initial string content This is a different string content |
For more details on C++ strings, you can have a look at the string class reference.
'Programming Language > c++언어' 카테고리의 다른 글
비주얼스튜디오 iostream.h 오류시 (1) | 2010.01.17 |
---|---|
객체 cin과 getline 차이점 (0) | 2010.01.17 |