Creating and initializing public variable

Posted on 2006-11-22
Last Modified: 2010-04-01

Assume I have a code like this:

static void main() {


int test() {


I want to define a variable in this code which can be accessible from main and int.

Also if I define a variable for example X in main and another X in test, how can I call test's X from main?

Question by:CSecurity
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2

Assisted Solution

xRalf earned 250 total points
ID: 17994202

define the variable as global before main

int x;
static void main() {


int test() {


If you define the variable X in test() it will be local variable for test() and it is impossible to call it from main. It's allocated on the stack and exists only during the function call.
LVL 17

Author Comment

ID: 17994206
But I heard something like test::X or something like this
LVL 17

Author Comment

ID: 17994252
is it possible?
LVL 12

Expert Comment

ID: 17994295
>> is it possible?
No it is not possible
LVL 12

Accepted Solution

rajeev_devin earned 250 total points
ID: 17994307
>> But I heard something like test::X or something like this
This is possible with static class members.
Or, namespace...


namespace test {
      int X;

static void main() {

      test::X = 0;

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question