Bool array

Are bool arays by default false? i mean if i declare a bool arr[n]; does it have n false entries by default?
No, it has a random value, depending on what the value of the previous variable that used that memory cell was.
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. (:
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/
If your array is global or static it will get initialized with default values.

Didn't know that. Why, actually?
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.
hm, ok, thanks!
Topic archived. No new replies allowed.