天天看点

[C++再学习系列] 变量与声明时初始化

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

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

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

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

<a></a>

1 #include &lt;errno.h&gt;

2 #include &lt;math.h&gt;

3 #include &lt;stdio.h&gt;

4 #include &lt;stdlib.h&gt;

5 #include &lt;string.h&gt;

6

7  void Print(int* buf, int len)

8 {

9 printf("Value(int)= ");

10 for(int i=0; i&lt;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&lt;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(&amp;v1, 1);

33

34 char v2 = '1'; // user initialization

35 Print(&amp;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

继续阅读