Home > Software engineering >  Forward variable declaration in C
Forward variable declaration in C

Time:09-24

I know what "forward function declaration" means, but I want get the same with variables.

I have this code snippet:

#include <iostream>

int x;

int main()
{
    std::cout << x << std::endl;   // I want get printed "2" but I get compile error

    return 0;
}

**x = 2;**

In the std::cout I want print "2" value, but trying to compile this I get this compile error: error: 'x' does not name a type.

While this doesn't appear somthing of programmatically impossible, I can't compile successfully.

So what is the right form to write this and obtain a forward variable declaration?

CodePudding user response:

Variable declarations need extern. Variable definitions need the type, like declarations. Example:

#include <iostream>

extern int x;

int main()
{
    std::cout << x << '\n';
}

int x = 2;

Normally you'd use extern to access a variable from a different translation unit (i.e. from a different .cpp file), so this is mostly an artifical example.

CodePudding user response:

You can declare

extern int x;

in this file, and in some other file

int x = 2;
  •  Tags:  
  • c
  • Related