#how to init static variables in main () ??

42 messages · Page 1 of 1 (latest)

kindred crescent
#

its causing error when i try to execute this code

class Solution{
public:
    static int i;

};
int main (){
int Solution::i = 0;
return 0;
}

it says

main.cpp: In function ‘int main()’:
main.cpp:7:17: error: qualified-id in declaration before ‘=’ token
    7 | int Solution::i = 0;
      |                 ^
topaz irisBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

kindred crescent
#

whats the error and how to resolve it

icy crane
#

because class Solution is defined in the global scope

kindred crescent
#

outside main ??

icy crane
#

so yes before main

kindred crescent
#

whats the order of execution of global space ?

#

before main ??

icy crane
#

global variables also before main starts

kindred crescent
#

main is defined in global space??

icy crane
#

yes

kindred crescent
#

got it

icy crane
#

functions can be either global, static functions in a class, or member functions in a class

kindred crescent
#

cus class defined in global space?

icy crane
#

you can define classes inside of functions

#

or onside other classes too

kindred crescent
kindred crescent
kindred crescent
kindred crescent
#

got it

#

thanks!

#

i shall close this tab

#

!solved

#

!solved

topaz irisBOT
#

Thank you and let us know if you have any more questions!

gray gazelle
kindred crescent
#

oh okay

kindred crescent
gray gazelle
#

doesn't matter what kind of function you define the class in

#

if you define a local class inside any function, that class cannot have static data members/static variables

kindred crescent
gray gazelle
#

never looked into any reason or rationale for that, but at the same time, do you really want that? and assuming you do, what would it mean? do you make the static data member behave more like static data members of non-local classes? or do you make them behave more like static local variables? even just that isn't clear
and considering that those things predate inline variables, how do you even initialize that static data member?

kindred crescent
#

i think also we have reserve extra memory for them, considering we may never execute that function, and their behavior could be the issue as you said.
i may never use it, but playing with it and understanding what made cpp devs to do so is also fun...

#

btw thanks for that @gray gazelle