Search code examples
c++stringoctal

int lambda expressions with string/octals? (C++)


I've been given an open book test, and been told I can use any resources I need to be able to answer the questions as it's more of an aptitude test - and one question has me really stumped.

The question asks to write a similar function to the given - which I'm sure I can do - but I can't find much information about what the function is doing, and given a small sample it's tricky to determine what is happening.

The question is as follows:

What does the program print? Please write an equivalent getValue function.

int t[]={1,2,3};
int getValue(int i)
{
  return "\5\3\8"[t[i]];    
}
void main()
{
  printf("%d",getValue(2));    
}

The program prints '0', which is the easy part. And I am tempted to answer with a simple method that returns just that. But I want a deeper understanding of what exactly is going on in the getValue function. My main curiosity is what the string part does in terms of the lambda expression, as \8 isn't a valid octal but seems to have some effect on the resulting values.

Not looking for a straight out answer (from what I gather that's why I use the homework tag), just a push in the right direction

Thanks for the help


Solution

  • The escape codes are not octal, I believe they are decimal. In any case, they are irrelevant as long as they occupy only a single byte.

    Tracing the execution of this is trivial. First, we consider a substitution for the parameter

    int t[]={1,2,3};
    int getValue()
    {
      return "\5\3\8"[t[2]];    
    }
    int main() //int, not void
    {
      printf("%d",getValue());    
    }
    

    The third value of t is 3, which yields the fourth character in the string. As the string literal is three characters, plus NULL terminator, then the fourth character is the NULL terminator. When converted to an integer, this value is zero. The printf call prints this integer correctly. A similar function would simply index into the string directly, for example.