cplusplus.com
C++ : Forum : Beginners : Declaring static variable
 
cplusplus.com
Information
Documentation
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs


post Declaring static variable

makan007 (77)
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 (6258)
I need to know is it better to declare static int goodAns = 1 or goodAns = 0?

It depends on what you need
screw (145)
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
Topic archived. No new replies allowed.