tags:

views:

127

answers:

7

I'm testing some code in C# from Visual Studio Express 2008:

delegate void Hm(int k);

static void Main(string[] args)
{
    char[] m = new char[10];

    m[0] = 'H'; m[5] = 'M';
    m[1] = 'o'; m[6] = 'u';
    m[2] = 'l'; m[7] = 'n';
    m[3] = 'a'; m[8] = 'd';
    m[4] = ' '; m[9] = 'o';

    unsafe { fixed (char* p = m) { Hm H = (k) => recurd(k, p); H(0); } }
    Console.ReadLine();
}

static unsafe int recurd(int i, char* p) 
{
      Console.WriteLine(p[i]); 
      if (i == 10) return 0; else return recurd(i + 1, p);    
}

It compiles perfectly, but if I make a little change in the "recurd" function:

static unsafe int recurd(int i, char* p) 
{
      Console.WriteLine(p[i]);
      i == 10 ? 0 : recurd(i + 1, p);
     // if (i == 10) return 0; else return recurd(i + 1, p);    
}

I got an error that says "Just the expressions of object assignment, call, increment, decrement and new can be used as instruction" (It's a translation from spanish).

Why do I get this error? How can I fix it?

+12  A: 

You're missing the "return" keyword:

return i == 10 ? 0 : recurd(i + 1, p);
Joel Coehoorn
it's true, I tried with the word "return" and I get the same error :(
yelinna
I solved it as you said. it works, thanks.
yelinna
A: 
i = (i == 10) ? 0 : recurd(i + 1, p);
sipwiz
+9  A: 

Try this:

static unsafe int recurd(int i, char* p) 
{
      Console.WriteLine(p[i]);
      return i == 10 ? 0 : recurd(i + 1, p);
}

It's complaining because you're not doing anything with the result of the expression.

Jonathan
+1 for being the only answer explaining the reason of the error message correctly.
0xA3
+1  A: 

This one

static unsafe int recurd(int i, char* p) 
{
      Console.WriteLine(p[i]);
      i == 10 ? 0 : recurd(i + 1, p);
     // if (i == 10) return 0; else return recurd(i + 1, p);    
}

won't work because it doesn't return anything.

crauscher
+1  A: 

Should be: return i == 10 ? 0 : recurd(i + 1, p);

You forgot to add your return in.

Correl
A: 

I tried: i= i == 10 ? return 0 : return recurd(i + 1, p);

and also i == 10 ? return 0 : return recurd(i + 1, p);

And I get errors.

But I tried: return i== 10 ? 0 : recurd(i + 1, p);

And It works!! Thanks Joel! Thanks Jonathan!

My mistake was thinking that the value was automatic returned and the word "return" was no necesary.

yelinna
If one of the answers solved the problem you should check its checkmark to accept it.
Dour High Arch
How do I do that? I'm a newbie here :)
yelinna
I did it. Thanks for the tip.
yelinna
A: 

I tried: i= i == 10 ? return 0 : return recurd(i + 1, p);

and also i == 10 ? return 0 : return recurd(i + 1, p);

And I get errors.

But I tried: return i== 10 ? 0 : recurd(i + 1, p);

And It works!! Thanks Joel! Thanks Jonathan!

My mistake was thinking that the value was automatic returned and the word "return" was no necesary.