Reputation: 457
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:
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
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
Reputation: 16540
the following proposed code:
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