简体   繁体   中英

Scope of Variable defined outside FOR loop?

The code below is used to replace continuous duplicate characters in a string with just one occurrence

e.g. "AAAABBBB" -> "AB" 

When I exit the for loop and print the value in temp, my expectation is to get the last letter of a string word. However, I get the first letter of the string (ie, with the value I initialized the temp).

string processString(string word) {
  char temp = word[0];
  string result = "";
  int size = word.size();
  for(int i=0, temp=word[0]; i<size; i++) {
    if(word[i] == temp) {
      continue;
    } else {
      result += temp;
      temp = word[i];
    }
  }
  cout << "TEMP : " << temp << endl;
  return result + temp;
}

Results:

WORD: CJXEJACCAJEXJF
TEMP: C
Output of function: CJXEJACAJEXJC

But the above code works perfectly fine if I remove the re-initialization in the for loop:

string processString(string word) {
  char temp = word[0];
  string result = "";
  int size = word.size();
  for(int i=0; i<size; i++) {
    if(word[i] == temp) {
      continue;
    } else {
      result += temp;
      temp = word[i];
    }
  }
  cout << "TEMP : " << temp << endl;
  return result + temp;
}

Results:

WORD: CJXEJACCAJEXJF
TEMP: F
Output of function: CJXEJACAJEXJF

Any clue why this is happening? Why does re-initializing it in the FOR loop makes such a big difference?

In the for loop, you are not re-initializing temp . You are creating a brand new int variable called temp that shadows the outer temp :

for(int i=0,temp=word[0];i<size;i++){
            ^^^^ brand new `temp'

Some compilers can be configured to warn about this:

$ g++ -Wshadow test.cpp
test.cpp: In function 'std::string processString(std::string)':
test.cpp:10:15: warning: declaration of 'temp' shadows a previous local [-Wshadow]
test.cpp:7:8: warning: shadowed declaration is here [-Wshadow]

The other answers are correct about shadowing, but just for reference, your function could be simply written as:

#include <string>
#include <iterator>
#include <algorithm>

std::string unique(std::string const &source)
{
    std::string result;

    std::unique_copy(src.begin(), src.end(),
                     std::back_inserter(result));
    return result;
}
for(int i=0,temp=word[0];i<size;i++)

That declares two variables, i and temp , scoped inside the for statement. This temp hides the one declared outside the for statement.

A new variable named temp is declared as an int in the for loop:

for(int i=0,temp=word[0];i<size;i++){

hiding the outer char temp variable, meaning the char temp variable is never used inside the for . The second version of the for loop does not declare a new temp variable by omitting the initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM