jjl3
jjl3

Reputation: 47

For loop setting variable to condition

The counter variable in my for loop gets set to the value of the condition upon first entering the loop. I have never heard of this happening, I wrote a very similar version of this code a month ago or so on this same system, and did not have this problem.

This is being compiled and built by Microsoft Visual Studio 6.0 Visual C++ on a 64-bit Windows Vista computer. I have commented out all of my unnecessary code and it still caused this error. The code, with all comments removed is below:

main.cpp:

#include "stdafx.h"

using namespace std;

int main(int argc, char* argv[])
{ 

cout<<"Simple Watch Region Test\n";
cout<<"-----------------------\n";

//get number of tracks
cout<<"  Enter Number of Tracks to Run: ";
unsigned int totalNumberOfTracksToRun;
cin>>totalNumberOfTracksToRun;

unsigned short currentTrack = 0;
cout<<"currentTrack starts at "<<currentTrack<<endl;

for( currentTrack; currentTrack < totalNumberOfTracksToRun; currentTrack++);
{

    cout<<"current is "<<currentTrack<<endl;

     }

    return 0;

}

stdafx.h:

#if !defined(AFX_STDAFX_H__9455C912_1697_486F_A680_AAE1D0B22611__INCLUDED_)
#define AFX_STDAFX_H__9455C912_1697_486F_A680_AAE1D0B22611__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <iostream>
#include <fstream>
#include <math.h>
#include <string>

And the output is:

Simple Watch Region Test
-----------------------
  Enter Number of Tracks to run: 5
currentTrack starts at 0
current is 5
Press Any Key to continue 

Thanks for your thoughts.

Upvotes: 1

Views: 130

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258618

You have a stray ;:

for( currentTrack; currentTrack < totalNumberOfTracksToRun; currentTrack++);
//                                                                         |
//                                                                       here

which means the for only increases currentTrack until it reaches totalNumberOfTracksToRun before going to the next lines.

Upvotes: 4

Joseph Mansfield
Joseph Mansfield

Reputation: 110728

You have a semicolon at the end of your for statement:

for( currentTrack; currentTrack < totalNumberOfTracksToRun; currentTrack++);
                                                     // get rid of this ---^

It means the for loop runs, doing nothing, until currentTrack becomes equal to totalNumberOfTracksToRun and only then is the following block executed. This is why it appears that currentTrack has instantly jumped to 5.

Upvotes: 5

Related Questions