user71812
user71812

Reputation: 457

How to debug this error in C: function definition is not allowed here?

I am new to programming and am taking edX's CS50 (Intro to Programming) class. There is this C code that I have been trying to compile, but always results in an error message that looks like this: error message

This is the code lines that I have been trying to compile:

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main (void)
{
   bool valid_triangle (float a, float b, float c);
   bool valid_triangle (float a, float b, float c)
  {
   // check positive values
     if ( a <= 0 || b <= 0 || c <= 0 )
    {
    return false;
     }
    //check two sides are longer
    if ( (a + b <= c) || (a+c <= b) || (b+c <= a))
    {
    return false;
    }

    //otherwise return true
     return true;
 }

}

Does anyone know what I did wrong and how to fix this error? Thanks a lot!

Upvotes: 0

Views: 2600

Answers (2)

Jinji
Jinji

Reputation: 11

Compiler error messages are your best friend, so use them to your advantage. Here, your error message triangle.c:9.6 tells you that your error is on line 9. Also, it spits out the string error: function definition is not allowed here.

In C, a procedural language, function definitions are not allowed inside of other functions.

To fix this, either define your function before your main() function, and then just call your valid_triangle function from your main function. Another way to organize your code would to put the valid_triangle function prototype before the main function, and then define the valid_triangle below the body of the main function.

Remember, the main() function is the point of entry for your program.

Upvotes: 1

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. performs the indicated functionality
  2. cleanly compiles
  3. displays one way to have sub functions in C

and now, the proposed code:

//#include <cs50.h>
#include <stdio.h>   // putc()
//#include <math.h>
#include <stdbool.h> // bool, true, false


bool valid_triangle (float a, float b, float c)
{
    // check positive values
    if ( a <= 0 || b <= 0 || c <= 0 )
    {
        return false;
    }

    //check two sides are longer
    if ( (a + b <= c) || (a+c <= b) || (b+c <= a))
    {
        return false;
    }

    //otherwise return true
    return true;
}


int main (void)
{
    float a = 1;
    float b = 2;
    float c = 3;

    if( valid_triangle (a, b, c) )
    {
       puts( "able to calculate triangle area" );
    }

    else
    {
       puts( "area of triangle cannot be calculated" );
    }

}

Upvotes: 1

Related Questions