Linked List Sort Help

I'm trying to find which student has the highest GPA and return the student name. I get an error that says N may be uninitialized and I am not sure why that is the case. Thank you for help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  string LinkedListStudent::findTopper()
{
    struct createNode *ptr, *N;
    int value;
    
    if (start == nullptr)
    {
        return "NA";
    }
    ptr = start;
    while (ptr != nullptr)
    {
        for (N = ptr; N != nullptr; N = N->next)
        {
            if (ptr->GPA < N->GPA)
            {
                value = ptr->GPA;
                ptr->GPA = N->GPA;
                N->GPA = value;
            }
        }
        ptr = ptr->next;
    }
    cout << "Student with highest GPA: " << N->Name << endl << endl;
    return " ";
}
> I get an error that says N may be uninitialized and I am not sure why that is the case

It should be just a warning (unless there was a compiler option to treat warnings as errors).

With this cleaner version of the code, an added benefit is that the spurious warning would go away:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// return name of topper or "NA" if the list is empty
std::string LinkedListStudent::findTopper() const // *** should be const
{
    if( start == nullptr ) return "NA" ;

    using node = createNode ; // *** createNode is a poor name for the type node

    const node* toppers_node = start ;

    for( const node* n = start->next ; n != nullptr ; n = n->next )
    {
        if( toppers_node->GPA < n->GPA ) toppers_node = n ;
    }

    // cout << "Student with highest GPA: " << toppers_node->Name << endl << endl;
    return toppers_node->name ;
}
Thanks for the help!
Topic archived. No new replies allowed.