-1

I am taking some C# tests online and I came across the following code:

using System;
namespace ProgrammingExercise
{
class FindOutput
    {
     static void Main(string[] args)
     {
     int num= 1234, r;
     while (num > 0)
      {
          r = num % 10;
          num = num / 10;
          Console.WriteLine(+r);
      }
      
      }
    }
}

I am a bit confused about the first line inside Main(). Does it mean that num=1234=r? I also don't understand why it's written +r... what does it do?

Edit

After the comments, it makes more sense and I'm writing the way I think it works:

  1. while evaluates to true (1234>0)
  2. r = 1234 % 10 = 4
  3. num = 1234 / 10 = 123 (can't result 123.4 because num is an int)
  4. 4 is printed ... the execution continues till the condition evaluates to false.
Community
  • 1
  • 1
  • [What does the unary plus operator do in C#?](https://stackoverflow.com/questions/727516/what-does-the-unary-plus-operator-do) – Rup Sep 30 '19 at 00:30

1 Answers1

3

The declaration

 int num= 1234, r;

is shorthand for

 int num= 1234;
 int r;

It does not assign r to 1234, you cannot change the value of numbers in C#.

The prefix operator + is not particularly useful, as it just means 'keep the current sign', in this case +r does not have any different effect to writing r by itself.

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171