ccompiler-errors

Compiler error about control reaches end of non void function


I'm getting a compiler error when compiling my code.

The problem is to find the largest prime factor for each of the fixed number of numbers from the user

The error I got -

Solution.c: In function ‘largest_prime_factor’:
Solution.c:35:1: error: control reaches end of non-void function [-Werror=return-type]
 }
 ^
cc1: some warnings being treated as errors

My code

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int largest_prime_factor(int a);
int check_prime(int b);

int main() {
    int t; 
    scanf("%d", &t);
    for (int a0 = 0; a0 < t; a0++) {
        long n; 
        scanf("%ld", &n);
        printf("%d\n", largest_prime_factor(n));
    }
    return 0;
}

int largest_prime_factor(int a) {
    if (check_prime(a) != 1) {
        for (int i = a - 1; i > 1; i--) {
           if (a % i == 0) {
                a = i;
           }
        }
        
        largest_prime_factor(a);
   }
   else {
       return a;
   }
}

int check_prime(int b) {
    int s = (int)sqrt(b);
    for (int i = 2; i <= s; i++) {
        if (b % i == 0) {
            return 0;
        }
    }
    return 1;
}

Solution

  • The problem is exactly what the compiler error says the problem is; in largest_prime_factor function you don't have a return in all paths, and since the return value is used by the calling function all paths must have a return value ( Thanks to @EricPostpischil for pointing out the proper standard rule) . In one case of the if you call recursively and don't have a return value for when the recursion completes. In the other pathway you return a. You need a return in all pathways.

    more visually:

    int largest_prime_factor(int a) {
        if (check_prime(a) != 1) {
            for (int i = a - 1; i > 1; i--) {
               if (a % i == 0) {
                    a = i;
               }
            }
            
            largest_prime_factor(a);
            // You need to return something here perhaps return largest_prime_factor(a)
       }
       else {
           return a;
       }
    }