user3137147
user3137147

Reputation: 363

How to declare global variable inside function?

I have problem creating global variable inside function, this is simple example:

int main{
   int global_variable;  //how to make that
}

This is exactly what I want to do:

int global_variable;
int main{
                   // but I wish to initialize global variable in main function
}

Upvotes: 19

Views: 80924

Answers (5)

Boldijar Paul
Boldijar Paul

Reputation: 5495

int global_variable;
int main()
{
    global_variable=3; // look you assigned your value.
}

Upvotes: 6

General Chaos
General Chaos

Reputation: 9

It's indirectly possible by declaring pointers global, and later assigning local variables to them, but sometimes, it may lead to situations where the pointed-to variable is inaccessible.

Upvotes: 0

Hamid
Hamid

Reputation: 1

    void foo(){
   static variable=10;
}

static means it's global

Upvotes: -3

Joseph Mansfield
Joseph Mansfield

Reputation: 110758

You have two problems:

  1. main is not a loop. It's a function.

  2. Your function syntax is wrong. You need to have parentheses after the function name. Either of these are valid syntaxes for main:

     int main() {
     }
    
     int main(int argc, const char* argv[]) {
     }
    

Then, you can declare a local variable inside main like so:

int main() {
  int local_variable = 0;
}

or assign to a global variable like so:

int global_variable;

int main() {
  global_variable = 0;
}

Upvotes: 22

sasha.sochka
sasha.sochka

Reputation: 14715

There is no way to declare it the way you want. And that's it.

But:

  • First, if you want you can declare it before the main body but assign a value to it inside main. Look Paul's answer for that
  • Second, actually there is no advantage of declaring variables the way you want. They are global and that means they should be declared in the global scope and no other places.

Upvotes: 12

Related Questions