Solved

Interesting Local Variable

Posted on 2004-09-27
10
308 Views
Last Modified: 2010-04-01
Dear Friends,

It is generally known that a local variable is not affected by other variable with the same name. The declared local variable prevails within its scope. The interesting thing is I declare a local variable of type int and name j. It is either within a function or a loop. As I peek in the codes in debug mode, j increases in every line eventhough it has no trace.


In UNIT* function j variable increases in every line. It had happened in EatSpaces function as well but I worked it out by changing the name to je. What is going on wrong?

I appreciate any comments,

Code is as follows

// TypeID_Deneme.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <Math.h>
#include "UNIT.h"

char* GetCharacters(const char* str,const char StopCharacter);
void EatSpaces(char* str);
UNIT* GetUnitType(char* str);


int main()
{

      string unit="meter > cm";
      const char* units=unit.c_str();

      char* ConvertFrom=GetCharacters(units,'>');
      EatSpaces(ConvertFrom);


      Pressure P;
      Length L;
      Energy E;
      Force F;
      Mass M;
      Volume V;
      Viscosity Vis;
      MassVolume M_V;
      Angle Ang;
      Area A;


      UNIT* pU=0;

      UNIT u[]={P,L,E,F,M,V,Vis,M_V,Ang,A};


      pU=GetUnitType(ConvertFrom);
      cout<<ConvertFrom<<" belongs to "<<pU->ClassName<<endl;

      if(pU!=0) for(int j=0;j<pU->ArrayLength;j++) cout<<pU->units[j]<<endl;            //to see if I can use the address of pointer

      return 0;
}


char* GetCharacters(const char* str,const char StopCharacter)
{
      int index=0;
      int i=0;
      char buffer[100]={' '};
      char* returnvalue;
      while(*(str+i)!='\0')
      {
            if(*(str+i)!=StopCharacter) buffer[i]=*(str+i);
            if(*(str+i)==StopCharacter)
            {
                  index=i;
                  returnvalue=new char[index];
                  strcpy(returnvalue,buffer);
                  return returnvalue;
            }
            i++;
      }

      return 0;
}




void EatSpaces(char* str)
{
      int i=0,je=0;
      while((*(str+i)=*(str+je++))!='\0')
      {
            if(*(str+i)!=' ') i++;
      }
      return;
}




UNIT* GetUnitType(char* str)
{
      Pressure P;
      Length L;
      Energy E;
      Force F;
      Mass M;
      Volume V;
      Viscosity Vis;
      MassVolume M_V;
      Angle Ang;
      Area A;



      UNIT u[]={P,L,E,F,M,V,Vis,M_V,Ang,A};


      int i=0,UnitTypeIndex=0;

      int NumberofUnits=ArrayLength(u);
      
      for(i=0;i<NumberofUnits;i++)
            for(int j=0;j<u[i].ArrayLength;j++)    //j equals to 1
                  if(u[i].units[j]==str)               //j equals to 2
                  {
                        UnitTypeIndex=i;
                        break;
                  }

                  return u[i].address;
}
0
Comment
Question by:MacroLand
10 Comments
 
LVL 3

Expert Comment

by:teratoma
Comment Utility
I don't think the difference in the debugging experience in EatSpaces was caused by changing "j" to "je".  I bet the loop was a for loop before it was a while loop and that caused the change.  The way in which the variable is incremented is also different.  In the for loop it's done naturally at the end of the loop (which the compiler is probably optimizing), and in the while loop it's done within the test (which the compiler probably isn't optimizing).  If you debug in assembler mode I'm pretty sure you'll see the code functioning correctly with the proper number of increments per loop.
0
 
LVL 4

Author Comment

by:MacroLand
Comment Utility
Regarding the below fragment of code :

 int i=0,UnitTypeIndex=0;

     int NumberofUnits=ArrayLength(u);
     
     for(i=0;i<NumberofUnits;i++)
          for(int j=0;j<u[i].ArrayLength;j++)    //j equals to 1
               if(u[i].units[j]==str)               //j equals to 2
               {
                    UnitTypeIndex=i;
                    break;
               }

               return u[i].address;

at first run in loop j=1 at if statement and j equals 2 at return statement (how it comes here is another discussion cause i =10)
at second run in loop j=3 at for (int j...) andj=5 at if statement and j=6 at return statement
at third run j=7 at for(int j..) and j=9 at if statement and j=10 at return statement

I couldnt work out but when I change variable name I is OK

So whats going on?

0
 
LVL 15

Expert Comment

by:efn
Comment Utility
There are some suspicious features in the code you posted, but aside from that, it depends on code you didn't post, which limits what we can do to debug it.  I suggest you post a minimal, compilable demonstration of the problem.  Also, what compiler are you using?
0
 
LVL 12

Assisted Solution

by:stefan73
stefan73 earned 50 total points
Comment Utility
Hi MacroLand,
>  for(i=0;i<NumberofUnits;i++)
>           for(int j=0;j<u[i].ArrayLength;j++)    //j equals to 1
>                if(u[i].units[j]==str)               //j equals to 2
>                {
>                     UnitTypeIndex=i;
>                     break;
>                }
>
>                return u[i].address;

If you expect the return to behave like your indentation suggests, you're in for a nasty surprise. Also, your break only leaves the inner loop.

Maybe you should simply place some print statements in your loop:

     for(i=0;i<NumberofUnits;i++){
          printf("i=%d\n",i);
          for(int j=0;j<u[i].ArrayLength;j++){    //j equals to 1
               printf("\tj=%d\n",j);
               if(u[i].units[j]==str)               //j equals to 2
               {
                    UnitTypeIndex=i;
                    break;
               }
          }
     }  
     return u[i].address;

...this will cast some light in the behaviour of your loop. Also be aware that the compiler can group or reorder statements when you activate the optimiser, so single-stepping statements in the debugger is sometimes a bit confusing.


Cheers!

Stefan
0
 

Expert Comment

by:s_senthil_kumar
Comment Utility
If you're using some version of a VC++ compiler, this is a special "feature". The scope of a "for" loop index variable is preserved beyond the "for" statement. According to the documentation,
<Quote>
Standard behavior is to let a for loop's initializer go out of scope after the for loop. Under /Ze, the for loop's initializer remains in scope until the local scope ends.

The following code will compile under /Ze but not under /Za:

int main() {
// int i;
   {
   for (int i =0; i < 1; i++)
      ;
   i = 20;   // i has already gone out of scope under /Za
   }
}
If you use /Zc:forScope, you will get a warning if a variable is in scope because of a declaration that was made in a previous scope...
</Quote>

There is a compiler switch  "/Zc:forScope", which gives a warning if you attempt to use the index variable outside the for loop's scope. Maybe you can try that.

Regards
Senthil
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Author Comment

by:MacroLand
Comment Utility
     UNIT u[]={P,L,E,F,M,V,Vis,M_V,Ang,A};

      int j=0;     // j is declared in here


      int i=0,UnitTypeIndex=0;      // j=1 here

      int NumberofUnits=ArrayLength(u);   //j =2 here
      
      for(i=0;i<NumberofUnits;i++)
      {
            for(j=0;j<u[i].ArrayLength;j++)
            {
                  if(u[i].units[j]==str)
                  {
                        UnitTypeIndex=i;
                        break;
                  }
            }
      }


this time using braces {} the return line is not met but after j is declared it begins to increase. I am using Visual C++ 6.0 and running code in debug mode to inspect j and the behaviour is unexpected.
0
 
LVL 4

Author Comment

by:MacroLand
Comment Utility
And some portion of UNIT.h is as follows



#include <Math.h>
#include <string>

//Define a base class for all units

using namespace std;      //if I remove this line it gives out errors that it does not recognize the string declerations

#define ArrayLength(a) sizeof a/sizeof a[0]



class UNIT
{
public:
      string* units, ClassName;
      int ArrayLength;
      UNIT* address;
      double* UnitRatios;


      UNIT()
      {
            units=0;
            address=0;
            ArrayLength=0;
            ClassName="";
            UnitRatios=0;
      }
      

      virtual ~UNIT()
      {
            units=0;
            address=0;
            UnitRatios=0;

      }
      
      
};





class Pressure:public UNIT
{
public:
      Pressure():UNIT()
      {

            string PressureStr[]={"Pascal","Atmosphere","Bar","Psia","mm-Hg","in-Hg",
                              "Torr","lb/ft2","lb/in2","kPa","MPa","mbar","kg/cm2","ton/ft2",
                              "ton/in2","ft/H2O (4°C)","inHg (0°C)","dynes/cm2"};
            double d_Pressure[] ={1, 9.86923266716013 *pow(10,-6), 0.00001,
                               1.4503824327685 * pow(10,-4), 7.5006168270417 *pow(10,-3), 7.12368581908572 *pow(10,-5),
                               7.5006168270417 *pow(10,-3), 2.08855472013367 *pow(10,-2), 1.45032632342277 *pow(10,-4),
                               pow(10,-3), pow(10,-6), pow(10,-2), (1.0197 *pow(10,-5)), 9.319664492 *pow(10,-6),
                               6.476683938 *pow(10,-8), 3.345600535 *pow(10,-4), 2.953337271 *pow(10,-4), 10,
                               0.0001020083889};

            int size=ArrayLength(PressureStr);
            units=new string[size];
            UnitRatios=new double[size];
            for(int i=0;i<size;i++)
            {
                  units[i]=PressureStr[i];
                  UnitRatios[i]=d_Pressure[i];
            }

            address=this;
            ClassName="Pressure";
            ArrayLength=size;
      }

      virtual ~Pressure()
      {
            delete[] units;
            delete[] UnitRatios;
            address=0;
      }

};
0
 
LVL 15

Accepted Solution

by:
efn earned 75 total points
Comment Utility
I tried your code in the same compiler and was unable to replicate the effect.  I saw j increase by 1 each time through the loop, just like it was supposed to.  So I have no idea what is causing what you see.  I still suggest you post something that is both minimal and compilable.  Often the exercise of constructing such a demonstration will increase your understanding.  For example, if you take something out and the problem goes away, that is a clue that what you just removed was related to the problem.

--efn
0
 
LVL 4

Author Comment

by:MacroLand
Comment Utility
Hi efn,

Thanks for ur try. If u give me your email I may post the project to you so that u can compile and run it.

Actually I started a new project of same type and copied all files to the new project and debug and run it and everything worked smooth. But to get a better knowledge or experience I am still concerned what was going wrong on that project.
0
 
LVL 15

Expert Comment

by:efn
Comment Utility
If you can't reproduce the problem in a copy, I probably won't be able to either.  I guess we just shrug and go on with our lives.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now