i've a Question

#include <cstdlib>
#include <iostream>

using namespace std;
int main()
{
int arg;
arg=-1;
{

char arg = 'A';
cout << arg << endl;
}
system("PAUSE");
return 0;
}

i wonder what is the block inside main do ??
please any one explain it to me
thanks in advance :)

i wonder what is the block inside main do ??
1
2
3
4
{
char arg = 'A'; // Creates a new object, of type char, with value 'A'.
cout << arg << endl; // Outputs it
}


This demonstrates shadowing; when you create an object inside a block, it is used in preference to one outside that block with the same name.
i've an Answer

This code demonstartes scopes of variable that is a variable in an inner declarative region hides a variable with the same name in an outer declarative region.

I could show a more interesting 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
#include <iostream>

int x = 10;

void f( char x = 'x' )
{
   std::cout << "x = " << x << std::endl;
}

int main()
{
   bool x = true;
   
   std::cout << x << std::endl;

   {
      enum { x = ::x };
      std::cout << x << std::endl;

      {
         char x = 'y';
         f( x );
      }
   }
}
Last edited on
closed account (zb0S216C)
mido91 wrote:
"i wonder what is the block inside main do ??"

It creates an anonymous-temporary scope. Objects/variables have the same life-time as the scope in which they are declared, unless you do something that breaks that. An attempt to access anything within a scope that no longer exists will generate an error.

It's common to see anonymous-temporary scopes so that temporary objects/variables are not sitting on the stack when their use has passed.

Wazzak
Last edited on
thank you guys for explaining it to me :)
Topic archived. No new replies allowed.