Search code examples
c++compiler-errorstriplet

Errors in Hackerrank compare the triplets code


I was doing the hackerrank triplet sum question and I found these errors but I dont know why these errors are coming. Can someone please give a little more insight about it and if possible link a video about the topics I should read in order to atleast get the code correct.

The code

#include <iostream>
using namespace std;
int compareTrip(int a[],int b[])
{
    int i=0,result1=0,result2=0;
    for(i=0;i<3;i++)
    {
        if(a[i]>b[i])
        result1++;

        if(a[i]<b[i])
        result2++;

        else {
        return 0;
        }
    }
}
int main()
{
    int i,a[3],b[3];
    for(i=0;i<3;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<3;i++)
    {
        cin>>b[i];
    }
    compareTrip(a[], b[]);

}

The Errors

Solution.cpp:30:19: error: expected primary-expression before ‘]’ token
     compareTrip(a[], b[]);
                   ^
Solution.cpp:30:24: error: expected primary-expression before ‘]’ token
     compareTrip(a[], b[]);
                        ^
Solution.cpp: In function ‘int compareTrip(int*, int*)’:
Solution.cpp:18:1: error: control reaches end of non-void function [-Werror=return-type]
 }
 ^

Solution

  • These first two errors occur because the compiler thinks you're trying to redefine the arrays a and b, which you've already initialized the at the beginning of main. When you call compareTrip() , you just need to pass in the names of those arrays as the two arguments.

    The error control reaches end of non-void function indicates that there is no return value at the end of the function at line 18. So you have a set of if/else statements in compareTrip() , but it's possible that you might get two arrays of integers where there is no match between a and b, and the function does not account for this condition. If this edge case happens, we'd find ourselves in an infinite loop, because the function would leave the for statement and never return. Because the return value is an int, you want to include a return statement outside of the for loop, before the final closing bracket },to avoid an infinite loop.

    You start learning more about C++ and its basic syntax through online courses like https://www.learncpp.com/,, https://www.sololearn.com/Course/CPlusPlus/, and https://www.codecademy.com/learn/learn-c-plus-plus. I believe the first two are free, and the third lets you start with a free trial. Happy learning!