Bool array

Jan 26, 2013 at 4:39pm
Are bool arays by default false? i mean if i declare a bool arr[n]; does it have n false entries by default?
Jan 26, 2013 at 4:50pm
No, it has a random value, depending on what the value of the previous variable that used that memory cell was.
Jan 26, 2013 at 5:21pm
Init them either way below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	bool boolA[ 10 ] = { false }; //Like this.

	bool boolB[ 10 ];

	for( int i = 0; i < 10; ++i ) //Or loop the array and init them.
		boolB[ i ] = true;


	//Output the arrays...
	std::cout << "Bool A:\n";

	for( int i = 0; i < 10; ++i )
		std::cout << boolA[ i ] << '\n';

	std::cout << "Bool B:\n";

	for( int i = 0; i < 10; ++i )
		std::cout << boolB[ i ] << '\n';


Hope this helps. (:
Jan 26, 2013 at 6:08pm
closed account (3TXyhbRD)
Depends. If your array is global or static it will get initialized with default values. Otherwise it won't.

Docs: http://www.cplusplus.com/doc/tutorial/arrays/
Jan 26, 2013 at 7:11pm
If your array is global or static it will get initialized with default values.

Didn't know that. Why, actually?
Jan 27, 2013 at 8:44am
closed account (3TXyhbRD)
Because the initialisation can be (and probably is) done at compile time or at worst at load time. Global values are not found on the stack, but in the global data section (which is a segment in assembly and later on in machine code). Same goes for static variables because all static variables share the same address which makes them "global" (or better said unique).

A difference between static and global variables is that globals are accessible from "outside" (outside a function) while static variables can be accessed from "outside" and "inside" (inside a function).

For instance, this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int a;

int func(int b){
    static int c;
    std::cout << "c is: " << c << std::endl;
    c = b;
    return c;
}

int main()
{
    std::cout << a << std::endl;
    std::cout << "func() is: " << func(10) << std::endl;
    func(100);
    return 0;
}

will always have the same output:
0
c is: 0
func() is: 10
c is: 10

Because c is a static int and will always have the same address whenever the function gets called.
Jan 28, 2013 at 3:58pm
hm, ok, thanks!
Topic archived. No new replies allowed.