Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. 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;
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading