#include "stdafx.h"
#include <iostream>
using namespace std;
int a=10;
void main()
{
 a=20;
 cout<<a<<endl;
 cout<<::a<<endl;
}
output: 20
           20

I actually want the "cout<<::a<<endl" output 10, but failed. Does "::a" mean a is in the gloable scope?
What should I have to change the code to make the second ouput 10 ? using "::a"

Dani AI

Generated

: the behavior you saw is correct — ::a refers to the name a in the global namespace, but in your original code you never created a separate local a. When you wrote a = 20; you changed the global a, so both a and ::a show 20. The scope-resolution operator :: gives the absolute (global) name, it does not protect a value from being overwritten beforehand. See the and name lookup/scope rules.

Two practical ways to get the output you want (global stays 10, local prints 20):

  • Introduce a local variable inside main (shadowing the global) so assignments affect the local a only; then ::a will still refer to the global 10. This is the approach suggested by .
  • Avoid assigning to the global at all (use a different name or pass values through function parameters). In general, reduce reliance on mutable globals for fewer surprises.

A few quick notes that expand on replies already here:

  • is right to flag the program signature: write a standards-conforming int main() and return a value rather than void main (see ).
  • stdafx.h is a Visual C++ precompiled-header convention; it is not portable and can be omitted in portable examples (see Microsoft docs on precompiled headers if using MSVC).

Summary: ::a points to the global a. To have cout << ::a print 10, do not overwrite that global — give main its own local a (or avoid modifying the global).

Recommended Answers

All 2 Replies

Create a local variable called a. Otherwise your global variables won't be hidden inside main.

#include "stdafx.h"
#include <iostream>
using namespace std;
int a=10;
void main()
{
 int a=20;
 cout<<a<<endl;
 cout<<::a<<endl;
}
#include "stdafx.h"
#include <iostream>
using namespace std;
int a=10;
[B] void[/B] main()
{
 a=20;
 cout<<a<<endl;
 cout<<::a<<endl;
}

BTW just as a reminder, main (void) doesnt return void , it returns an int which is the signal to the operating system about the execution status of the program. A zero is returned on flawless execution while a non-zero return implies there was some problem faced while executing the code.

Hope it helped, bye.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.