post  Declaring static variable

makan007 (37)   Link to this post
1
2
3
4
5
6
7
8
9
10

	static int goodAns = 1;
	
	if (goodAns % 2 == 0)
		cout << "Congrats" << endl << endl;
		
	else
		cout << "Good Job" << endl << endl;
		
		goodAns ++;

I need to know is it better to declare static int goodAns = 1 or goodAns = 0?
What is the diff?
Bazzy (3164)   Link to this post
I need to know is it better to declare static int goodAns = 1 or goodAns = 0?

It depends on what you need
screw (112)   Link to this post
Hello!

Ok, what don't you understand?

The static keyword ensures that the variable preserves its value between function calling.

http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

The % operator divides the goodAns by 2 and return the fractional part. So 1 / 2 would be 0.5 but it will be made round to 0.

1
2
3
4
else
		cout << "Good Job" << endl << endl;
		
		goodAns ++;


The goodAns++ instruction is always executed! It doesn't belong to the if statement.
If you want it then you should use braces.
Last edited on

Registered users can post in this forum.