Search code examples
c++compiler-errorsreturncompiler-warnings

Cannot understand error: "warning: control reaches end of non-void function [-Wreturn-type]"


I have been learning c++ recently. When I tried to run the following lines...

#include <iostream>

short a = 0;
short b = 1;
short c, i;

void Fibonacci(){
    std::cout << a;
    std::cout << b;
    while (a <= 100){
        c = a + b;
        a = b;
        b = c;
        std::cout << c;
    }
}

int prime_number(short a){
    if (a == 1){
        std::cout << "It's a prime number\n";
    } else{
        for (i = 2; i < a; i++){
            if ((a%i) == 0){
                std::cout << "It's a prime number\n";
                std::cout << "The given number is divisible by " << i << "\n";
                return 0;    
            }
        }
        std::cout << "It's not an prime number";
    }
}

int main(){
    short user_input;
    std::cout << "Press 1 for Fibonacci and 2 for prime number";
    std::cin >> user_input;

    if (user_input == 1){
        Fibonacci();
    }
    if (user_input == 2){
        std::cout << "Type the number to check whether it's prime";
        std::cin >> a ;
        prime_number(a);
    }
}

...I get an error saying:

In function ‘int prime_number(short int)’:
Function.cpp:37:1: warning: control reaches end of non-void function [-Wreturn-type]
   37 | }

I searched various platforms for the answers, but I couldn't understand what really happens here. It's an error because the compiler cannot find whether the function has an end or not. Can someone help me understand the error and solve it?


Solution

  • As Elliott in the comments has said the warning you are getting is not going to affect your program at all. It's recommend that you return something since you function has a return type of integer.

    Below is a easy fix to get rid of the warning. :)

    Old Code:

    if (a == 1)
    {
        std::cout << "Its a prime number\n";
    }
    

    New Code without the Warning:

    if (a == 1)
    {
        std::cout << "Its a prime number\n";
        return 0;
    }