Please help me out!

I am currently looking at http://www.cplusplus.com/doc/tutorial/constants/

My question is about [Typed constant expressions]

The example chart inserted 'const double' and 'const char' out the 'int main()'

But I see no difference between when it is out the 'int main()' and when it is in it.

Besides, I haven't read nothing of 'const double' and'const char' so far.

Where can I find it in tutorial?
I think the main difference is the scope of the constants are different.
Where the constants declared outside of main are global, but the ones declared inside of main are not global, they are local to the main function.
The difference is the scope.

Lets say this for example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// the is the global scope

#include <iostream>

int i = 42;

int func()
{
	return i;
}

int func2()
{
	return i;
}

int func3();

int main()
{
        // this is main's scope
	int i = 16, j = 8;
	std::cout << i << std::endl;	// prints 16
	std::cout << ::i << std::endl; // use scope operator to print global i: prints 42
	std::cout << func() << std::endl; // prints 42
	std::cout << func2() << std::endl; // prints 42 as well
	std::cout << func3() << std::endl; // ERROR: j can only be accessed in main and in enclosing scopes
       // enclosing scope
	if (true)
	{
		int x = 128;
		std::cout << j << std::endl;	// prints 8
		std::cout << x << std::endl;	// prints 128
	}

	std::cout << x << std::endl;		// ERROR: where is x???
	return 0;
}

int func3()
{
	return j;	// where is j???
}

It is a bad idea to pollute the global namespace(an implicit scope). You may have int i defined in one file and in another, then using i will be ambiguous.
Last edited on
Topic archived. No new replies allowed.