c++ variable keeps resetting instead of incrementing? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
void RetailerOrder::addItem(Product* p)
{
bool space = false;
int counter = 0;
while ((space == false) && (counter < manifest.size()))
{
if (manifest[counter] == nullptr);
{
manifest[counter] = p;
space = true;
}
counter++;
}
if (space == false)
{
cout << "no space" << endl;
}
}
Why does the counter reset to zero with each pass through the while loop? If I use it as it is, only the last product that I enter gets stored in the array because i is always 1. Is there a way to let the counter increase.

if (manifest[counter] == nullptr); // << see here
{
manifest[counter] = p;
space = true;
}
That semi-colon at the end of your if statement means "if condition, do nothing".
Then the braced scope following that executes always.
It should instead be:
if (manifest[counter] == nullptr)
{
manifest[counter] = p;
space = true;
}
As an aside, I'm not a big fan of things like:
if (space == false) ...
since, if you name you boolean values intelligently, you can avoid the comparisons:
if (! foundSpace) ...
The intelligent naming means that the boolean variable itself should be readable, such as with foundSpace or haveFinished or userIsClinicallyInsane. Once it is, you don't need to compare it to boolean constants at all.
That greatly reduces the code size and avoids the reductio-ad-absurdum situation where you don't know when to stop comparing booleans to constants:
if ((((haveFinished == true) == true) != false) == true) ...
As a second aside, I value my vertical space greatly when looking at code and there are ways to simplify your code which make it shorter and, in my opinion, easier to understand.
Since you're only using space as a way to insert the item and exit the loop prematurely, you could use something like:
void RetailerOrder::addItem (Product* p) {
// Check every possible slot.
for (int i = 0; i < manifest.size(); i++) {
// If one free, use it and exit.
if (manifest[i] == nullptr) {
manifest[i] = p;
return;
}
}
// None were free, complain bitterly.
cout << "no space" << endl;
}
Still, that's a stylistic approach of mine and you should feel free to ignore it if you disagree.
The "multiple return points are bad" crowd may not like it but that's usually because they don't understand the reason why it's considered suspect, the inability to easily see the many code paths. With a function of this size, it's not really a issue.

Related

while exercise with return in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I've just started coding in c++ and now I have an exercise that I can't do because the code seems to not work.
I've to find the max and the min with a sequence of n numbers (in this case i already know that they are 4). I've to use while.
I've just started so I don't know how return properly works...
there aren't syntactical errors but when I run it ask me the number but then it says that the algorithm ends with 0 value.
Here's the code, if you can help me thank you!
#include <iostream>
using namespace std;
main ()
{ float mag,min,i,a;
mag=0;
min=0;
i=0;
while (1)
{
if (i<5)
{ cout<<"insert a number"<<endl;
cin>>a;
if (i = 0)
{ mag=a;
min=a;
}
else
{ if (a<min)
{ min=a;
}
else
{ if (a>mag)
{ mag=a;
}
}
}
i=i+1;
}
else
{ cout<<"maggiore= "<<mag<<endl<<"min= "<<min<<endl;
}
return 0;
}
system ("pause");
}
I see at minimum one problem:
if (i = 0)
This is assignment of i to 0 and compare the result of assignment, which is always false if you assign a 0.
I believe you want only compare and not assign, so you have to use:
if ( i == 0 )
The next problem is
return 0;
This will always end the current function, if the function is main(), it will terminate your program. In your case, you can simply remove the return statement, as in main it will return 0 by default if the function ends.
But if you use
while (1)
without any return, your program runs endless. I don't know what is the expected behavior.
Rest looks fine.
Hint: Your indentation is a bit special. :-)
1st it should be i==0 not i=0 in the if
2nd you should place that return 0 after that cout maggiore or it will close after the first loop
3rd you don't need that system pause there. It does literally nothing. You should either remove it or place it exactly before the return.

Declare int variable aux a.length = (); Or use o.length () in all loops? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I wonder which is faster: Say I'm working with some text (30 characters), which would be better? And with a lot of text which would be better?
1-
int tam = text.length();
for(int i=0;i<tam;i++)
{
//something here//
}
2-
for(int i=0;i<a.length();i++)
{
//something here//
}
and also comparing these two:
1-
for (int i = 0; i < b.length(); i++)
{
aux = a.find(b[i]);
if (aux == -1)
{
sucess = 0;
break;
}
else
{
a.erase(aux,1);
}
}
2-
for (int i = 0; i < b.length(); i++)
{
if (a.find(b[i]) == -1)
{
sucess = 0;
break;
}
else
{
a.erase(a.find(b[i]),1);
}
}
Both first are the better approach.
On the first example you are checking if i<a.length() is true on every cycle. That means that you are going to execute a.length() for every iteration. If the variable a is not changed, it is unnecessary and the better approach is to calculate before and use that value.
Note that if the variable a is changed inside, placing i<a.length() might be the correct approach. It depends on your problem.
On the second example it is the same basics. You avoid useless calculations because you won't need to calculate a.find(b[i]) again inside the else.
As a general rule of thumb, as computations get bigger, more complex, and more frequent you want to minimize your unnecessary calculations. This means that storing something that needs to be calculated in a variable may speed up the process.
In both of your examples, for extremely large numbers,
int scratch = big.length();
for(int i=0;i<scratch;i++){
//body//
}
is usually faster.
In the future, general questions like this tend to belong in something like the Code Review Stack Exchange.

Unexpected changing of C++ constant integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

how to get correct answer merge 2 sorted arrays?! C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
i wrote a little algorithm for marge to sorted array. but i have problem with that.
#include <iostream>
using namespace std;
int main() {
// main function started form here:
int firstArray[10] = {1,3,5,7,9,11,13,15,17,19};
int secondtArray[10] = {2,4,6,8,10,12,14,16,18,20};
int mergedArray[20];
int firstCounter=0 , secondtCounter=0 , mergedCounter=0;
while(firstCounter < 10 && secondtCounter < 10){
if(firstArray[firstCounter] < secondtArray[secondtCounter]){
mergedArray[mergedCounter] = firstArray[firstCounter];
firstCounter++;
} else {
mergedArray[mergedCounter] = secondtArray[secondtCounter];
secondtCounter++;
}
mergedCounter++;
}
while(firstCounter < 10) {
mergedArray[mergedCounter] = firstArray[firstCounter];
firstCounter++;
mergedCounter++;
}
while(secondtCounter < 10) {
mergedArray[mergedCounter];
secondtCounter++;
mergedCounter++;
}
for(int j=0; j<20; j++){
//cout << mergedArray[j] << endl;
}
cout << mergedArray[19];
return 0;
}
in outpout for array mergedArray[19] i get something like this: 2686916!!!
i don't know why i get this value. how can i fix that. and why i get this value.
Typo in last while. You may increase your warning level to let your compiler show you your typo (warning: statement has no effect [-Wunused-value]).
while(secondtCounter < 10) {
mergedArray[mergedCounter];
secondtCounter++;
mergedCounter++;
}
should be
while(secondtCounter < 10) {
mergedArray[mergedCounter] = secondtArray[secondtCounter];
secondtCounter++;
mergedCounter++;
}
As pointed out by WhozCraig's comment, you're not assigning any value to mergedArray[19] because you left out the assignment part of the statement.
Since you haven't assigned a value, it's printing out whatever value happens to be at that memory address from previous usage. If you run your program (as it's currently written) several times, you'll see that the number there might change. Also, if you'd printed out the values in mergedArray before assigning anything, you'd see more such meaningless (to you in the current application) numbers.

For loop variable going to hell for seemingly no reason? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.
The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:
void enterdata(float dpoint,int num){
autodata[num] += dpoint;
}
float autocorr(){
float autocorrelation = 0;
for(int a = 0; a<SIZEX; a++)
{
for(int b = 0; b<SIZEY; b++)
{
if(grid[a][b] == reference[a][b]){autocorrelation++;}
}
}
autocorrelation /= SIZEX*SIZEY;
autocorrelation -= 0.333333333333;
return autocorrelation;
}
for (long z = 0.0; z<MAXTIME; z++)
{
for (long k=0; k<TIMESTEP; k++)
{
grid.pairswap();
}
if (z == autostart_time)
{
grid.getreference();
signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
}
if ((z*10)%dataint == 0)
{
if (signal == 1) {
//!!! this is the important segment!!!
cout << z << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}
From the "important segment" marked in the code, this is my output:
3200 before,
1059760811 after,
0.666667 (number returned by function)
Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.
I have no idea how to fix this, or what is going on. Help?!?!?
Thanks!
Looks like you may have a Stack Overflow issue in your enterdata function.
Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.
#WhozCraig is right, a stack overwrite by a called function seems the most likely explanation.
You should be able to find out in your debugger how to break on any change to the memory at address of z, this will quickly provide an exact diagnosis.
For Visual Studio (for example), see here.