tags:

views:

139

answers:

2

Help me understand this piece of code -

After the first iteration the value of PlcCode becomes A1*. How come? Shouldn't it be A*?

   Code = "A1";
   char Wild = '*';
   TDataString PlcCode(Code);

   for (int i = (Code.Len() - 1); i >= 0; i--)
   {    
      PlcCode[i] = Wild;
   }
+3  A: 

I see two possible scenarios:

  • TDataString is overloading operator[ ] and uses index 1 as a start (most likely to simulate another language).
  • Code.Len() does not give you the predictable output.

Of course, those are speculations, since I don't have any other information.

LiraNuna
If it was using base 1 subscripting, the result would be "*1" - subscript 2 is never overwritten by the loop (assuming Len returns 2).
Steve314
If TDataString overloads [] to mimic arrays, then it starts from 0 not 1 as far as I understand from the code. I agree with your overall speculations :)
AraK
Sorry - that should be "*" (possibly followed by junk).
Steve314
Could be combination of both as far as we know.
LiraNuna
+3  A: 

Another possibility

  • TDataString is storing non-null terminated data, and has a templated operator= accepting byte arrays.

This way, you could think of the code as

   TDataString Code(3);
   Code[0] = 'A';
   Code[1] = '1';
   Code[2] = '\0';

   char Wild = '*';
   TDataString PlcCode(Code);

   for (int i = 2; i >= 0; i--)
   {              
      PlcCode[i] = Wild;
   }


Imagine the following implementation of TDataString

struct TDataString {
  typedef unsigned char TElement;

public:
  TDataString(std::size_t n):data(n) { }

  template<typename T, std::size_t N>
  TDataString(T const (&d)[N]):data(d, d+N) { }

  TElement &operator[](std::size_t i) {
    return data[i];
  }

  std::size_t Len() const { return data.size(); }

private:
  std::vector<TElement> data;
};

Using that class, we can assign "A1" to Code, and it will give it a length of 3, and then executing the loop's first iteration will get us to A1*.

Johannes Schaub - litb
Thank you very much.
Andman
This only makes sense if the length for Code *includes* the null terminator, which would be unusual to say the least. Note - the length of Code is two, and the first subscript overwritten is (Code.Len () - 1) which I would expect to be one.
Steve314
@Steve314, what i mean with "storing non-null terminated data" is that the data is not necessarily null terminated (as is usually the case with "normal" strings). That is, you could have done `Code[2] = 'B';` and length is still 3. Otherwise, i think simply naming the class `TString` would be a better choice
Johannes Schaub - litb
From the tracing-The Code.Len() returns 3.litb is right.
Andman
@litb - OK, makes sense
Steve314