Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
Console.WriteLine(Abs(-7) + " " + Abs(7));
int Abs(int n)
{
if (n < 0)
{
return -n;
}
}It does not compile
- Expecting
7 0: a method does not return0on its own; the compiler requires areturnon every path and stops the build withCS0161. - Expecting a failure only when
Abs(7)runs: the compiler checks every path of the method before the program starts, so nothing is printed.
- How would you fix
Absso that the program builds and prints7 7? - Why is the method still rejected if it ends with
if (n >= 0) return n;?