Unepected output

Can anyone see whats wrong with this code?

It all seems pretty logical to me but i'm getting a very strange answer:

PLEASE ENTER A FIRST NUMBER:
4
PLEASE ENTER A SECOND NUMBER:
7
4349962


1
2
3
4
5
6
7
8
9
10
11
12
13
14
 int sum_from_to(int first, int last)
{
int result;

if (first < last)
for (int n = first; n <= last; n++)
	result += n;
else
for (int n = last; n <= first; n++)
	result += n;

return result;

}
result is uninitialized and contains garbage.
You didn't initialize result

i.e.

int result = 0;
I initialized result to 0 int result = 0 and it cleared the madness. What does the compiler just allocate random memory to you and unless you initialize it who knows whats going to be in there?

This frightens me terribly.

What happens if im trying to read in something from stringstream or from something else and am testing to see if has worked or not!?!?!? (Shock horror!?!?!?)

Does stringstream initialize a variable or when it inputs in it i.e if i try and input an int from stringstream an it fails how can you test for this?

I need to sleep.
Last edited on
What happens if im trying to read in something from stringstream or from something else and am testing to see if has worked or not!?!?!? (Shock horror!?!?!?)


You could use the stringstream::fail() method.

i.e.

1
2
3
4
5
6
7
8
9
std::stringstream myStream(someString);

float hopefullyWillBeAFloat;
myStream >> hopefullyWillBeAFloat;

if(myStream.fail())
{
   //wasn't a float
}


What does the compiler just allocate random memory to you and unless you initialize it who knows whats going to be in there?

You can think of it like that though in reality it gets initialized with whatever is on the stack. Debug builds tend to zero initialize variables so it's suggested to run your program at least once in a Debug where a difference in behaviour will suggest a bug. As a rule of thumb it's best to initialize all variables.
Last edited on
OK thanks. Good to know this for future.
What does the compiler just allocate random memory to you and unless you initialize it who knows whats going to be in there?

Well, to be precise about it, it's undefined. The C++ standard doesn't require an implementation to do any built-in initialisation.

In practice, this means that it will depend on the implementation - i.e. the compiler - that you're using. And many compilers will do different things depending on whether you're doing a release or a debug build, based on what the people writing it thought would be most useful to developers.

In short, you should initialise all your variables, and never rely on the compiler doing it for you. It's a bit of a pain, but there it is.

Of course, in the modern, object-oriented world, your classes have constructors, which do the initialisation. This way, when you create a new object, you know the initial state of it.
Topic archived. No new replies allowed.