• Advertisement
Sign in to follow this  

Quirk in "if ()" function that I don't get

This topic is 4261 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
	int entry;
	vector<int> numbers;
	while (cin >> entry)
		numbers.push_back(entry);
	int sum = 0;
	for (vector<int>::size_type index = 0; index != numbers.size(); ++index) {
		if (sum != 0) {
			sum += numbers[index];
			cout << sum << endl;
			sum = 0;
		} else {
			sum += numbers[index];
		}
	}
	if (sum > 0)
		cout << sum << endl;
	return 0;
}

In working with the above code I noticed a weird quirk. The above works perfectly, however...
#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
	int entry;
	vector<int> numbers;
	while (cin >> entry)
		numbers.push_back(entry);
	int sum = 0;
	for (vector<int>::size_type index = 0; index != numbers.size(); ++index) {
		if (sum = 0) {
			sum += numbers[index];
		} else {
			sum += numbers[index];
			cout << sum << endl;
			sum = 0;
		}
	}
	if (sum > 0)
		cout << sum << endl;
	return 0;
}

...this code yields the error message "Possibly incorrect assignment in function main()" for line 17, and then fails to properly add the adjacent vector elements when executed. I have noticed that all of my programs fail if I test a variable against 0 as I did in the later (x = 0). Logically they seem identical to me. Can anyone explain why this happens?

Share this post


Link to post
Share on other sites
Advertisement
x = 0 sets x to 0 and evaluates to 0, making the test always false.
x == 0 compares x with 0.

The compiler is warning you against this extremely common error.

And if is not a function.

Share this post


Link to post
Share on other sites
Quote:
Original post by industrialplaid

*** Source Snippet Removed ***

I have noticed that all of my programs fail if I test a variable against 0 as I did in the later (x = 0). Logically they seem identical to me. Can anyone explain why this happens?


Do you by any chance mean "if (sum == 0)" ? (notice the extra '=' sign)?

With just one = sign, the if statement will assign 0 to sum (just like "sum=0;") -

[edit: hell's bells! 2 other replies while writing mine. =) everyone's quick on the draw!]

Share this post


Link to post
Share on other sites
AHH! Thank you guys. It was driving me nuts. Now it makes perfect sense!

Fruny, thanks for the correction. I should have said, "...the if STATEMENT."

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement