C/C++ Why Does My C++ Code Result in an Infinite Loop?

  • Thread starter Thread starter fluidistic
  • Start date Start date
  • Tags Tags
    C++ Logic
AI Thread Summary
The discussion revolves around a C++ code snippet that enters an infinite loop due to variable shadowing. The code attempts to generate random numbers between 1 and 3 and write them to a file until the new number differs from the previous one by either +1 or -1. The issue arises because the variables `x` and `xold` are redefined within the loop, causing the original values to be masked. This results in the loop condition never being satisfied, leading to continuous iterations. A suggestion is made to remove the `int` declarations inside the loop to resolve the issue. Additionally, it's advised to initialize `xold` to a value outside the random range to enhance randomness and avoid predictable outcomes. After implementing these changes, the code functions correctly.
fluidistic
Gold Member
Messages
3,928
Reaction score
272
I don't understand why I enter in an infinite loop with the following code:
Code:
#include <iostream> //for cout
#include <cstdlib> //for rand()
#include <ctime> // for time()
#include <fstream> //to write into a text file
using namespace std;

static const int M = 3;

ofstream myfile;
int main()
{
	srand(time(0)); // set initial seed value to system clock
		myfile.open("data.txt", ios::app);
int x=0;
int xold=0;
int i;
do
{
	int xold=x;
	int x = rand() % M+1;
	myfile << x << endl;
	i++;
}
while(x-xold!=1 && x-xold!=-1);
cout << "It took" << i << "iterations"  << endl;


return 0;

myfile.close();
}

The idea is to generate a random number between 1 and 3, write it into a file. Repeat until the new random number differs by either +1 or -1 from the previous random number. With the current code, the loop never ends and in a matter of a few seconds my file.txt is filled by 1's, 2's and 3's up to several Mb's.
As I understand it, my do {...} wile(x-xold!=1 && x-xold!=-1) should continue when x-xold is not equal to 1 and when x-xold is not equal to -1. So if I get xold=0 and x=1, then x-xold=1 and the loop should stop because the first condition is not satisfied... but it doesn't stop at all.
I guess my logic is flawed but I'm blind and don't see it. Any help will be appreciated.
P.S.:I started c++ 5 days ago for fun.
 
Technology news on Phys.org
fluidistic said:
Code:
int x=0;
int xold=0;
int i;
do
{
	int xold=x;
	int x = rand() % M+1;
	myfile << x << endl;
	i++;
}
while(x-xold!=1 && x-xold!=-1);

You have defined two variables called xold, and two called x. Delete the "ints" inside the do-while loop.

FWIW a sensible compiler should give you a warning message if you "mask" one variable with another.
 
  • Like
Likes 1 person
Also, if you want to make the numbers be truly random, I would make the number int xold be something like 10, something far enough away from the range of the random numbers.

Otherwise, you will always be starting with xold = 0, and you will be more likely to break with the results 0, 1; (unless that was your intention).

Writing to console worked in C#...
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFPlayground
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int x = 0;
            int xold = 10;
            int i = 0;

            do
            {
                xold = x;
                x = random.Next(1, 4);
                Console.WriteLine(x);
                i++;      
            }
            while (x - xold != 1 && x - xold != -1);
            Console.WriteLine("It took {0} iterations", i);

            Console.ReadLine();
        }
    }
}
 
  • Like
Likes 1 person
AlephZero said:
You have defined two variables called xold, and two called x. Delete the "ints" inside the do-while loop.

FWIW a sensible compiler should give you a warning message if you "mask" one variable with another.
Ah I see! I didn't even notice this. The program works fine now! Thanks!
TheDemx27 said:
Also, if you want to make the numbers be truly random, I would make the number int xold be something like 10, something far enough away from the range of the random numbers.

Otherwise, you will always be starting with xold = 0, and you will be more likely to break with the results 0, 1; (unless that was your intention).

Writing to console worked in C#...
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFPlayground
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int x = 0;
            int xold = 10;
            int i = 0;

            do
            {
                xold = x;
                x = random.Next(1, 4);
                Console.WriteLine(x);
                i++;      
            }
            while (x - xold != 1 && x - xold != -1);
            Console.WriteLine("It took {0} iterations", i);

            Console.ReadLine();
        }
    }
}
Well spotted, thank you!
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Back
Top