Trying to assing a value of a static member of a struct

So i have a simple struct with only a single static varialbe as shown below:

1
2
3
4
5
6
7
struct X{
	static int k;
};

int main(){
	X::k =2;
}

This does not compile
i have tried many things form cppreference like
 
	int X::k =2;

None of them compile
 
static int k;


just declares the variable k - it doesn't define it. You also need to define it as

1
2
3
4
5
6
7
8
9
struct X {
	static int k;
};

int X::k = 0;

int main() {
	X::k = 2;
}

Last edited on
why doesn't this works

1
2
3
4
5
6
7
8
9
struct X {
	static int k =0;
};

//int X::k = 0;

int main() {
	X::k = 2;
}
When having a static variable in a struct/class, within the struct the variable is declared without initialisation and the variable is defined (and initialised) at global level - usually just before main().

If you're using C++17, you can use inline:

1
2
3
4
5
6
7
struct X {
	inline static int k = 0;
};

int main() {
	X::k = 2;
}


or if you want a const static, then

1
2
3
4
5
6
struct X {
	const static int k = 99;
};

int main() {
}

@seeplus thanks man you are a life saver
Topic archived. No new replies allowed.