Identifier is not being defined

Why is this not working? I am pretty new to programming and was just wondering why this isnt working, I could get it fixed tmr by my teacher but I'd like to have it fixed now so I can continue on with the rest of the program.

1
2
3
4
5
6
  int FindLength(int Start,int End)
{
	if (End<Start) int Length = 2400-Start+End;
	else if (End>=Start) int Length = End-Start;
	return Length;
}Put the code you need help with here.
The variable "Length" is not in scope when you say return Length;

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int FindLength(int Start,int End)
{ //begin scope of FindLength (well, technically, the 'int Start' and 'int End' above fall into this scope)
        int Length;

	if (End<Start)
        { //begin scope of 'if' block
            Length = 2400-Start+End;
        } //end scope of 'if' block
	else if (End>=Start)
        { //begin scope of 'else if' block
            Length = End-Start;
        } //endscope of 'else if' block

	return Length;
} //end scope of FindLength 


Check out the section on "Scope of variables" here: http://www.cplusplus.com/doc/tutorial/functions/

EDIT:
To show scope more explicitly, I added curly braces even though you don't need them if your "if" and "else" only apply to single statements. Since Length is now being declared at the function's scope, the return statement can see it.
Last edited on
Length variable will be destroyed after leaving any branch of ifs.
You probably want to do:
1
2
3
4
5
6
7
8
9
int FindLength(int Start,int End)
{
    int Length;
    if (End<Start) 
        Length = 2400-Start+End;
    else if (End>=Start)
        Length = End-Start;
    return Length;
}
Yeah Thank you guys for the help, problem solved.
Topic archived. No new replies allowed.