• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 359
  • Last Modified:

Interesting Local Variable

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
MacroLand
Asked:
MacroLand
2 Solutions
 
teratomaCommented:
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
 
MacroLandAuthor Commented:
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
 
efnCommented:
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
stefan73Commented:
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
 
s_senthil_kumarCommented:
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
 
MacroLandAuthor Commented:
     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
 
MacroLandAuthor Commented:
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
 
efnCommented:
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
 
MacroLandAuthor Commented:
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
 
efnCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now