Problem with sending a signed int to another signed int. Almost random number given.
The following code is filled with holes (not that it would not make it run, it runs but with a strange problem), because it is a snippet from a bigger block of code of another program. I am doing this to clean up code. My aim in the following section of code is check to see how many elements are in a number within the vector ivar, then combine all of them into one number. So if ivar[0] = 2 and ivar[1] = 4, then the code would combine them and it would be 24. I was using math.h to do exponent operations, but it required changing several variables to doubles, and it would have made bigger problems as the code grew. So just to simplify things I made the function powerfunc. Powerfunc seems to work fine, its the loop in main that does not seem to. Loop outpus correct values but the values that are being added together gives out almost random numbers. Here is that output followed by some more details:
Code:
1 Code:
#include <iostream> |
You never initialized itemp_store:
Code:
int itemp_store = 0; Also your complete outer for-loop (for (int a=0...)) is needles, because you only run this loop until a==ivar.size()-1 and do nothing else, so why not simply set a=ivar.size()-1 or maybe even better let the "b-loop" run as long as b<ivar.size(): Code:
for ( int b = 0, power = powerfunc(10,a); b < ivar.size(); b++, power = (power/10) ){ |
Thank you it works, and yes that loop works too, I'll use it. BTW why do I have to initialize it? The following works, which is more or less what I tried to do:
Code:
int i; |
> The following works
no it does not work, you are just getting lucky. > Or is just not good practice to do what I did, for the error I found? it is not good practice to use uninitialized variables, because there is absolutely no gurantee as to what they will hold initially |
xhi I know your intelligent when it comes to programming, so the following question does not try to undermine you. I'm not sure what you mean by getting lucky. It works or doesn't. Why does my last piece of code work?
|
You were lucky that 'i' was initialized to 0 (and not to another value). Not sure, but I have the feeling that some languages do default initializations of variables and others don't.
|
Wim is correct.
in c and c++ the declaration Code:
int x; so if any operation other than assignment happens to a varible first, then you should initialize the variable to 0 (or an otherwise suitable value).. hth |
All variables should always be expressly initialized to known values.
|
Quote:
Code:
int x; |
All times are GMT -5. The time now is 06:32 PM. |