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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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 learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

636 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