Click here to Skip to main content
15,392,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public String getage(int age)
        {
            if (age > 60)               //  Error : Not all code paths return a value.
                return "senior";
            else
                if (age >= 40 && age <= 59)
                    return "middle aged";
                else
                    if (age >= 20 && age <= 39)
                        return "adult";
                    else
                        if (age >= 12 && age <= 19)
                            return "teenaged";
        }




it do not get the error in it..please help a newbee..thx
Posted
Comments
Ankur\m/ 25-Dec-10 5:13am
   
You need an else condition. Or just add 'return ""' at the last.
#realJSOP 25-Dec-10 7:14am
   
Don't vote correct answers with a 1. It may not be the answer you wanted, but they ARE correct based on your question.

Your If-case does not handle the scenario if age is less than 12. Look closely. Thus, for age < 12, your code does not return anything and hence the error.
   
I guess, you are trying to know the reason of the error message.

As your method returns a String, the complier expects that each and every condition should return a String.

Look the following piece of code in your example:

C#
if (age >= 12 && age <= 19)
     return "teenaged";


It doesn't have an "else" block, so, the compiler doesn't see any String value getting returned in this situation. So, it is not able to compile the class and showing the error.

I hope I was able to help you.
   
Shikhar,

You already received enough answers; they tell you that you need "else" and this is all correct.

However, I personally think this is just a technical detail.

You problem is rather conceptual: you ignore children (totally, with newborn, infants...), but you should not. Unlike most of the software developers, children still have unclouded mind.

So, here is an ultimate answer for you: if you just accidentally forgot about "else" -- add it, if you ignore children -- rethink your life.

Best wishes! ;)
   
v3
Comments
JF2015 25-Dec-10 12:41pm
   
Although the OP might not say this answer was very helpful, I like the way you think. Have my 5.
Sergey Alexandrovich Kryukov 25-Dec-10 16:57pm
   
Better take look at my recent Answer with AgeLimitException -- it makes sense; something important we all forgot. Should be noted...
Espen Harlinn 26-Feb-11 11:24am
   
Good reply - my 5
Sergey Alexandrovich Kryukov 26-Feb-11 17:54pm
   
Or, it's my old post about children!
Thank you, Espen!
--SA
C#
public String getage(int age)        
{            
  if (age > 60) //  Error : Not all code paths return a value.                
    return "senior";            
  else
    if (age >= 40 && age <= 59)                    
      return "middle aged";                
    else
      if (age >= 20 && age <= 39)                         
        return "adult";                    
      else
        if (age >= 12 && age <=19)                            
          return "teenaged";
        else
          return "else";      
}


This code should not cause the error. It handles every case that could occur.
   
v4
Comments
shikhar gilhotra 25-Dec-10 4:34am
   
this is a tricky but incorrect answer.....pls help aainest my query..thx
JF2015 25-Dec-10 4:49am
   
If this doesn't help you, then you need to tell us in more detail what you want.
#realJSOP 25-Dec-10 8:14am
   
I voted your question up to counteract the idiot's invalid 1 vote.
Manfred Rudolf Bihy 25-Dec-10 9:05am
   
Same from me 5+
Still the first that should have been pointed out to OP is the single point of entry single point of exit thing.
Sergey Alexandrovich Kryukov 25-Dec-10 15:52pm
   
There was a vote of 1? Right, what a stupidity! I'm counteracting, too!
Sergey Alexandrovich Kryukov 25-Dec-10 15:55pm
   
...well for a record, whole idea of the code in Question is not too clever, but that is not our fault.

Anyway, if you said "child" instead of "else", would make some sense, because... -- "What is your age, sir?" -- "I'm 'else'" would certainly cause strong cognitive dissonance :-).
JF2015 25-Dec-10 16:08pm
   
I posted "else" since the method could be used with negative integers. I didn't want to correct all of his code but only show the solution for the imminent problem.
Sergey Alexandrovich Kryukov 25-Dec-10 16:59pm
   
Good point! We all missed it, but! then the type should be unsigned, agree? At to invalid values, see my new Answer with AgeLimitException -- makes sense.
Thank you.
fjdiewornncalwe 25-Dec-10 18:23pm
   
@JF2015: "I posted else...": Perhaps something more appropriate for the negative argument values would be something like "glint in daddy's eye" or "oops, it broke"... Cheers and have another 5 for the downvoter's idiocy...
JF2015 25-Dec-10 18:45pm
   
@Marcus Kramer: Sure, you are right - I was not feeling that creative today :)
Your complete condition looks "not so good" maybe you try something like this.

C#
public string GetAge(int age)
 {
     if (age >= 60)
         return "senior";
     if (age >= 40)
         return "middle aged";
     if (age >= 20)
         return "adult";
     if (age >= 12)
         return "teenaged";
     // now all code paths will return a string - compiler satisfied
     return "child";
 }
   
v4
Comments
#realJSOP 25-Dec-10 8:14am
   
I voted your question up to counteract the idiot's invalid 1 vote.
Manfred Rudolf Bihy 25-Dec-10 9:04am
   
Ditto 5+
pasztorpisti 25-Dec-10 11:17am
   
Removed the unnecessary 'else' keywords to make it more readable. I think that embedded branching always make code unreadable, so this is definately the best answer. A similar scenario is when someone uses embedded if-else branches to check something inside a loop. In that case the unreadable code can be avoided with 'continue' statements similarly to the returns here. If someone needs 'single point of exit' function then the embedded if-else branches is the way to go but we usually follow the rule of putting braces around both the if and else codeblocks if one of them is consisting more then 1 line of code.
pasztorpisti 25-Dec-10 12:42pm
   
@johannesnestler: Don't use hungarian notation. Iam hungarian, and I know its bad! :) Maybe the "p" prefix for pointers can be useful but you can live even without that!
Sergey Alexandrovich Kryukov 25-Dec-10 13:23pm
   
pasztorpisti, I support your point about not using "else", even though the extra assignment can be considered more redundant than that, but it adds to supportability and readability (I'm afraid some readers of such could will be irritated).

I know that hungarian language is one of the most complex and hard-to-learn (maybe even in comparison with my native language, I don't know), but I've read a few (really great) hungarian books in translation and could naturally feel the wonderful richness of the language even after translation. To the opposite case, hungurian notation served as a week tool to compensate the extreme lame of the languages with poor typing model, such as C and, in fact, C++ (how much more reasons for further irritation!).

Thank you.
johannesnestler 25-Dec-10 16:01pm
   
thank you for your votes and comments
@SAKryukov - before we start a flame war, let's just say you have strong arguments against hungurian notation, so for sure you know the pro's and decided for yourself not to use.
I support not using HN in any public Interface (API, class whatever).
I do use kind of HN for all internal variables, it saves me from finding new names when converting and keeps my objects in the IntelliSense sorted by type. But of course (as you guessed) I come from C/C++ and finally it's just because I'm used to it...
Marry Christmas @ all!
Sergey Alexandrovich Kryukov 25-Dec-10 16:51pm
   
There is no way I can get into a flame war about such a non-so-serious subject as proper naming convention (for C# I support Microsoft naming recommendations with few exclusion, for a record). I did not even express my assessment of HN, I only put historical background and wanted to have a nice friendly chat with Hungurian person pasztorpisti -- simply, please read literally what is written, no more Are we good? I think we are.

Mary Christams and best wishes in New Year to you both, as well as every one!
Toli Cuturicu 25-Dec-10 17:21pm
   
Ok. Issue solved.
pasztorpisti 25-Dec-10 17:54pm
   
:):):) Marry Christmas! :):):)
Yep, there is no flame. Its just talking about something, this is how we learn! Anyway hungarian is really one of the riches languages. Sometimes films that are relatively unsuccessful somewhere else become very-very successful in hungary because of the cool translation. An example is "The Adventures of Ford Failane" :D:D:D Its just 5/10 outside Hungary and I think its at least 9 here. And heared somewhere that somteimes Flintstones was translated back to english, it had brilliant and funny rhymes in hungarian. And yep, its fair that I should give a reasoning when I make strong statements like "hungarian notation is bad". Back in C and later in C++ I used it heavily, until someone has pointed out that it has no real benefit. I could not say anything that I lost by leaving hungarian notation. Another argument is that when I started to work on a bigger codebase with lot of ppl working on it I started to find things like this in the codebase (this is probably the aftermath of bulk refactorings):
bSomething = 2
:D:D:D Despite this Iam ready to accept if someone likes this notation, its a matter of taste!
My problem with the above solution is not that it uses unnecessary assignments, but the fact that it is buggy and it was already able to deceive two ppl (3 including me).
Try this:

C#
public string getage(int age)
{
    string result = "senior";
    result = (age < 60) ? "middle aged" : result;
    result = (age < 40) ? "adult"       : result;
    result = (age < 20) ? "teenaged"    : result;
    result = (age < 13) ? "child"       : result;
    return result;
}


No matter what happens, a string will be returned. Your particular problem is that you need an else after the last if statement that returns an appropriate string indicating an error condition.



EDIT =============

Corrected for reverse logic.
   
v4
Comments
Manfred Rudolf Bihy 25-Dec-10 9:06am
   
Clear and concise! 5+
Single point of exit, that's how I like my functions! :)
pasztorpisti 25-Dec-10 11:29am
   
Single point of exit is good for lenghty functions with fancy logic, but in such a simple function its better to use a few checks and returns like johannesnestler did below. It makes code more readable. And this code performs a few unnecessary assignments, so I gave a 4.

EDIT: Just changed my vote to 1 because I found out that the code isn't working. It gives you "middle aged" even if age is 1!
JF2015 25-Dec-10 17:41pm
   
Have my 4, since although the code doesn't work it showed the OP how it should be done - he could figure out the logic on his own.
Sandeep Mewara 26-Dec-10 0:50am
   
Looks like in a hurry you made a small mistake. For example, Age 10 will pass as true for all the conditions and it will return 'middle aged' at the end all the time!
#realJSOP 26-Dec-10 5:49am
   
@everyone that noticed - I fixed the reverse logic thing. I apologize if the mistake caused rivers to overflow their banks, or cities to crumble under the weight of such a grievous error. However, if there has been even one regime change via violent overthrow, you can't blame that on me.
RaviRanjanKr 26-Dec-10 6:01am
   
Excellent Answer, 5+
pasztorpisti 26-Dec-10 7:00am
   
A bug was able to hide from seemingly veteran programmers (even from you) in this small function. :D Revised the vote to 4.
Sandeep Mewara 26-Dec-10 12:06pm
   
"I apologize if the mistake caused rivers to overflow their banks, or cities to crumble under the weight of such a grievous error" :)
BTW, I thought you wouldn't come online anymore for the day!

Missing case



Now I understand that there can be another valid use case.
This is maybe what Shikhar really wanted but failed to express.

Forgive me Shikhar! May be you're not ignoring children; may be you're -- just the opposite -- overly protective if them?

Forgive me, everyone! Silly me!

We all missed yet another important option.
Here is how:

C#
public class AgeLimitException : System.ApplicationException {
    internal AgeLimitException(
         int actualAge,
         string comment) : base(comment) {
              this.fActualAge = actualAge;
    } //AgeLimitException
    internal AgeLimitException(int actualAge) {
        this.fActualAge = actualAge;
    } //AgeLimitException
    public int ActualAge { get { return fActualAge; } }
    int fActualAge;
} //class AgeLimitException

//...

public string GetAgeString(int age) {
    if (age > 60)
        return "senior";
    else if (age >= 40 && age <= 59)
        return "middle aged";
    else if (age >= 20 && age <= 39)
        return "adult";
    else if (age >= 12 && age <= 19)
         return "teenaged";
    else
         throw new AgeLimitException(age,
             "Parential consent required");
} //GetAgeString


Beyond the jokes: this is another valid use case of not returning in every case: throwing an exception.

Thank you. ;)
   
Comments
fjdiewornncalwe 25-Dec-10 19:01pm
   
Nice catch... I agree with you, but I don't know why you were not voted well for the answer. I'm never quite sure why a "3" vote makes any sense unless it is someone trying to get their own answer to show higher on the list without being really blatant about it.
Sergey Alexandrovich Kryukov 25-Dec-10 22:18pm
   
Marcus, I don't understand you: who do you think voted "3" for what? I did not...
I have no idea who voted 3 for my answer; and I would not see any reason; I would suggest that not very good vote needs proper honest comments pointing out the problems of the post, so it could be argued. Whatever...
Sergey Alexandrovich Kryukov 26-Feb-11 14:39pm
   
I misplaced my comment to yours a while ago, above...
--SA
Espen Harlinn 26-Feb-11 11:28am
   
Another good effort - my 5
Sergey Alexandrovich Kryukov 26-Feb-11 14:40pm
   
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900