I have a function:

static int Example(int a, int b) { if (a>b) return 1; else if (a<b) return 2; else if (....) return 3; ... } 

In which something is checked with the help of ifs and then the value from these ifs is taken and returned.
But an int function should always return a value, that is, after passing, I have to write another return , but if I write it, the value will be returned only from this return. How can I return values ​​from ifs only?

  • 2
    and the problem is what? And more about, но если я его напишу возвращаться будет значение только из этого return'а but something you are not doing. Then bring all the code ... - pavel
  • understood how to fix the need to have a variable with = 0; and after each if branch, change its value and at the end write return c; - Draktharon
  • @ RustemValeev: Where is the variable c in your code? - VladD
  • And think what your function should return if none of the conditions are met. - VladD
  • one
    @RustemValeev there are 2 fundamentally different opinions: "the exit point (return) should be one" and "it is necessary to leave the function where it has logically completed the work". Both options with their cockroaches, the truth is somewhere in between. - rdorn

4 answers 4

 private static int Example(int a, int b) { if (a > b) return 1; if (a < b) return 2; return 3; } 

Just the compiler does not understand that either <or> or ==

  • He could understand, but since such a consideration helps in the overwhelming minority of cases, the compiler does not do this. - VladD
  • one
    Generally speaking, not necessarily either < , or > , or == . Take for example double.NaN . Any comparison with it will return false . An example . - Dmitry D.
  • @ Dmitry D. Speech about a specific code from the TS (int) - Leonid Malyshev
 switch (a.CompareTo(b)) { // a < b case -1: return 2; // a>b case 1: return 1; // a=b (или что то другое) default: return 3; } 
     static int Example(int a, int b) { if (a>b) return 1; else if (a<b) return 2; else if (....) return 3; else // если ни одно из условий не подходит, то вернуть, например, 0 return 0; } 
       static int Example(int a, int b) { int result = 3; if (a>b) result = 1; if (a<b) result = 2; return result; }