博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[C++再学习系列] 变量与声明时初始化
阅读量:7232 次
发布时间:2019-06-29

本文共 2037 字,大约阅读时间需要 6 分钟。

      未初始化的变量常常会导致一些奇怪的bug,有时还真不好调式。养成在初始化变量的习惯有利于减少编程错误,提高程序质量。

      C++提供了构造和析构函数,其中构造函数就是为初始化而设计的;对于内置变量(char,int,long等)的初始化C++无能为力,其默认行为是未初始化,故其值依赖于变量类型(是否为static)和编译器。

      本文中将讨论两类基本变量:标量和数组,标量指单一变量,数组本质上就是一整块内存空间(别忘了memset)。其他数据结构均基于这两类基本变量,一般由库提供,比如著名的C++ STL容器。

 

声明时初始化的格式直接参见代码中的注释。

 

 
1
#include
<
errno.h
>
2
#include
<
math.h
>
3
#include
<
stdio.h
>
4
#include
<
stdlib.h
>
5
#include
<
string
.h
>
6
7
 
void
Print(
int
*
buf,
int
len)
8
{
9
printf(
"
Value(int)=
"
);
10
for
(
int
i
=
0
; i
<
len;
++
i)
11
{
12
printf(
"
%d
"
, buf[i]);
13
}
14
printf(
"
\n
"
);
15
}
16
17
 
void
Print(
char
*
buf,
int
len)
18
{
19
printf(
"
Value(char)=
"
);
20
for
(
int
i
=
0
; i
<
len;
++
i)
21
{
22
printf(
"
%c
"
, buf[i]);
23
}
24
printf(
"
\n
"
);
25
}
26
27
int
main(
int
argc,
char
**
argv)
28
{
29
printf(
"
scale variable:\n
"
);
30
//
1. scale variable
31
char
v1;
//
not initialization. Value depends on compiler
32
Print(
&
v1,
1
);
33
34
char
v2
=
'
1
'
;
//
user initialization
35
Print(
&
v2,
1
);
36
37
char
*
v3
=
new
char
;
//
not initialization. Value depends on compiler
38
Print(v3,
1
);
39
40
char
*
v4
=
new
char
();
//
zeroing initialization. value is 0;
41
Print(v4,
1
);
42
43
char
*
v5
=
new
char
(
'
A
'
);
//
user initialization
44
Print(v5,
1
);
45
46
int
*
i5
=
new
int
(
1243214
);
//
user initialization
47
Print(i5,
1
);
48
49
50
printf(
"
array variable:\n
"
);
51
//
2. array
52
char
a[
10
];
//
not initialization. Value depends on compiler
53
Print(a,
10
);
54
55
char
b[
10
]
=
{};
//
same as {0}; zeroing initialization.
56
Print(b,
10
);
57
58
char
b1[
10
]
=
{
'
a
'
};
//
b[0]='a', other is 0!
59
Print(b1,
10
);
60
61
char
*
c
=
new
char
[
10
];
//
not initialization. Value depends on compiler
62
Print(c,
10
);
63
64
char
*
d
=
new
char
[
10
]();
//
zeroing initialization.
追海逐风
证实,g++无此功能
65
Print(d,
10
);
66
67
//
char* e = new char[10]('a');
//
Error: ISO C++ forbids initialization in array new
68
//
Print(e, 10);
69
70
return
0
;
71
}
72
http://www.cnblogs.com/zhenjing/archive/2010/10/12/1848616.html
你可能感兴趣的文章