I'm pretty new to C programming and I had a question as to why a sample code I was given runs the way it does. I'm learning about function prototypes. Can someone give me a run down on the order in which this compiles?
//TwoFunctions - All code split into two user-defined functions
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//function prototypes
//Calculates and displays the total and avergae of two numbers
void CalcAvg(double tot);
double CalcTotal();
int main()
{
double totl;
totl = CalcTotal();
CalcAvg(totl);
printf("Your total is %.2f\n", totl);
return 0;
}
CalcTotal()
{
double val,
num,
total;
printf("Please enter a number: ");
scanf(" %lf", &num);
printf("Please enter another number: ");
scanf(" %lf", &val);
total = val + num;
return total;
}
void CalcAvg(double tot)
{
double avg;
avg = tot/2;
//printf("Your total is %.2f\n", tot);
printf("The average of the two numbers is %.2f\n", avg);
return;
}
If it makes any sense, for the most part I understand and can write a program like that, however I am a little unclear as to the the steps involved, the calls, and the order in which the compiler compiles the program. Can someone shed a little light on this for? Greatly appreciate it!
Suggested changes:
/*
* Calculates and displays the total and avergae of two numbers
*/
#include <stdio.h>
//function prototypes
double CalcAvg(double tot);
double CalcTotal();
int main (int argc, char *argv[])
{
double tot = CalcTotal();
printf("Your total is %.2f\n", totl);
printf("The average of the two numbers is %.2f\n", CalcAvg(totl));
return 0;
}
double
CalcTotal()
{
double val, num, total;
printf("Please enter a number: ");
scanf(" %lf", &num);
printf("Please enter another number: ");
scanf(" %lf", &val);
total = val + num;
return total;
}
double
CalcAvg(double tot)
{
return tot / 2.0;
}
Function declaration and function prototypes have their differences. A declaration simply means introducing the function (its name) to the compiler before it's usage, similar to a variable; just the function return type is specified. A prototype is where you specify every type the function is associated with i.e. argument type(s) and the return type.
Say you've an add that adds two ints and returns an int. This is a declaration
int add();
while this is a prototype
int add(int, int);
In C89 having a declaration isn't necessary at all. You may just use (call) add(3, 5) and the compiler should infer argument types from the function call and since no return type is known int is assumed. From C99 onwards declaration before usage was made mandatory. Still declaring a prototype isn't necessary. Thus the declaration would be
Note that the argument types isn't part of the declaration. C99 didn't allow the return type to be assumed implicitly as int, it has to be specified in the declaration. Still a function prototype isn't mandatory. Even today C11 doesn't expect a prototype but just a declaration.
Function prototypes were introduced in ANSI C (1989) where a function's declaration can have the argument and return types specified. Though it was never made mandatory for all functions. Only for variadic functions it's mandatory since C89 to declare a function with prototype.
As for your specific program, you declared two functions (one with prototype and one without [see Kerrek SB's comment]) and the used them in main; after main's definition, you've defined the two functions earlier declared.
your questions expects a lot of different topics to be discussed.
1)how compilation takes place? Check This Link For compilation Process
2) how are functions called ? Function Call
read these two links if still you have doubts be more specific on what you want.
Please follow the changes as suggsted by #FoggyDay.
The execution of any program is started from main. so compiler will first find out main and start execution from there.
int main()
{
double totl;
totl = CalcTotal(); /*As a function call to CalcTotal(); function is made here, the
execution is main is suspended and compiler tries to find
CalcTotal()'s definition and runs the whole function and return
value is store in "totl" variable. (Here the return value of
CalcTotal() is double as defined by function's return value.)*/
/*As soon as CalcTotal() function returns, the compiler again comes back to main()
where it suspended the execution and resumes the execution. saves return value of
CalcTotal() in "totl" and jumps to next statement.*/
CalcAvg(totl); /*Again in this statement, a function call to CalcAvg(totl) function
is made here so main()'s execution will be suspended and execution
jumps to CalcAvg(totl) function. The compiler continues to execute
this function until it returns*/
/*When CalcAvg(totl) returns, the execution of main() is again reumed from here*/
printf("Your total is %.2f\n", totl); //This line prints totl
return 0; //main returns and this defines end point of the program.
}
Generally, execution of a program starts from main and goes step by step until a function is called inside main. As soon as any function is called, execution is redirected to that function until that function returns.
Related
C learner here.
I've made a program that generates a random number that receives input for the user to guess the number.
When I try to write the code this way:
#include<stdio.h>
int random(){
int num = random();
return num;
}
int main(){
int guess;
printf("I have a number, try guess it!");
scanf("%d", &guess);
if(guess == random()){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
My compiler gives a Segment fault error.
But when I write the program like this, it compiles and runs with no error.
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! \n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
Can somebody tell me how to fix the segment fault error I mentioned above? Or how I can write this code properly? Any help is appreciated! <3
In case somebody asks about my system environment, I am using Windows 10 and a online compiler from this website: https://www.onlinegdb.com/online_c_compiler
In the function random() you have written in the first code, the line
int num = random()
is again calling the random function which in turns calls random again and it will result in an infinite loop which might leads to segmentation fault.
So change the function name to some other name like "random_number_generator".
And also avoid using the function names which are already present keywords or inbuilt function names.
Take a look at the second one:
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! \n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
When this compiles, even through online gdb, you should see: main.c:13:18: warning: implicit declaration of function ‘random’ [-Wimplicit-function-declaration].
The reason for this is random comes from <stdlib.h>. You can find this by doing man random if you have man, otherwise you can check here: http://man7.org/linux/man-pages/man0/stdlib.h.0p.html.
Under it you can see the deceleration long random(void). So the reason the second one works is you are using the random function from stdlib.h and implicitly declaring it since you aren't explicitly including that library (which you should).
The reason the first doesn't work is because you are using recursion, which I'm assuming you're not meaning to do. If you're new to programming you may be unfamiliar with that term, but basically it means you are calling the same function from within the function itself. You have no stopping criteria, so it continues until it would cause a stack overflow, resulting in a seg fault.
When you do:
int random(){
int num = random(); // who do I call? stdlib or myself? it's me.
return num;
}
C doesn't know that the outer random is different than the random called within it. To change this, you need to rename the outer function like so:
int my_random_func(){
int num = random(); // calls the stdlib random implicitly
return num;
}
This is a good reason to also explicitly #include <stdlib.h>, so you don't implicitly use a function you aren't trying to.
#include <stdlib.h>
int my_random_func(){
int num = random(); // calls the stdlib random explicitly
return num;
}
When you explicitly use the headers you need, you can get better failures as well:
#include <stdlib.h> // explicitly state I want the stdlib header.
int random(){
int num = random(); // which do I call? There is my declaration and stdlib's...
return num;
}
This results in the following error message:
main.c:12:5: error: conflicting types for ‘random’
int random(void) {
^~~~~~
In file included from main.c:10:0:
/usr/include/stdlib.h:321:17: note: previous declaration of ‘random’ was here
extern long int random (void) __THROW;
^~~~~~
Hopefully this helps you see why yours isn't working and why you should try your best to explicitly include headers you are looking for.
Here is the code from my program that has a issue:
#include "stdio.h"
int main(void)
{
int funcnum;
printf("Welcome \n");
printf("Please enter a number\n");
scanf("%i",&funcnum);
switch(funcnum) //funcnum is the variable you are checking for a match
{ //Open curly!
case 1: // is funcnum==1?
printf("You entered 1. This is now the Turkey Time function.\n"); // if funcnum==1, this will happen.
{
//DECLARE the "cookTime" function.(Above, outside the MAIN function)
//It will return a float, and is expecting two floats.
float cookTime (float);
//Below is a "global" variable -meaning available to all functions. These are declared outside of any function.
float cTim;
float weight;
printf("Welcome to the turkey timer...\n");
printf("Please enter a turkey weight \n");
scanf("%f",&weight);
cookTime (weight); //Calling (jumping to) the cookTime function and sending it "weight" variable.
printf("Cooking time is %.1f minutes.\n\n",cTim); //printing the returned value cTim.
printf("\tThank you for choosing the MaiCorp Timing System, don't forget the gravy! \n");
//DEFINE the function. Note -no semicolon. (just like in main's definition above!)
float cookTime (float w)
{
cTim = w*15;
return cTim; //We are sending cTim back to where we left Main.
}
}
break; //break makes the statement end and jump out of the curlies.
case 2: // is funcnum==2?
printf("You entered 2. This is now the Area function.\n");
{
//DECLARE the "area" function.(Above, outside the MAIN function)
//Looking at the declaration we can see that this function will return an int, and is expecting two int's.
int area (int, int);
//Here we declare a global variable. Meaning a variable that is available to all functions. These are declared outside of any function.
int ans;
int len,wid;
printf("Welcome to the rectangle area calculator...\n");
printf("Please enter a length\n");
scanf("%i",&len);
printf("Please enter a width\n");
scanf("%i",&wid);
area (len,wid); //Calling the "area" function, sending it the len and wid integers..
printf("Area is %i.\n",ans); //printing the returned value "ans"
//DEFINE the area function. Note -no semicolon. (just like in main's definition above!)
int area (int L, int W)
{
ans = L*W;
return ans;
}
}
break;
default: //default catches all non matches.
printf("You did not enter 1 or 2, meaning that you are not running a function this time.\n");
break;
} //close curly!
return 0;
}
When I run this program, the gcc version 4.6.3 compiler gives this:
main.c: In function 'main':
main.c:35:21: error: static declaration of 'cookTime' follows non-
static declaration
float cookTime (float w)
^~~~~~~~
main.c:17:21: note: previous declaration of 'cookTime' was here
float cookTime (float);
^~~~~~~~
main.c:67:19: error: static declaration of 'area' follows non-static
declaration
int area (int L, int W)
^~~~
main.c:47:19: note: previous declaration of 'area' was here
int area (int, int);
^~~~
exit status 1
This program is written in C in case anyone needs to know the programming language that the program is written in.
I have tried to fix the program by putting in "{}"'s and other code but it came to be of no use (meaning that the error did not resolve).
It would be great if a reputable programmer can assist me with this issue.
It looks like you are declaring a function within the main...? That is not only bad practice, but judging by the code there it looks like it's illegal. Unless you put static in front of it.
If you want to use the function, do NOT put it's return type before using the function. Instead of:
int area( int L, int W);
use
area(int L, int W);
Really weird to define a function within the main. Like I said, I don't think it's allowed, but if you REALLY want to do it, I would suggest putting static in front of the function.
Better yet, make a Name_goes_here.h file and put the functions in there. Then,
#include "Name_goes_here.h"
and use the functions like I told you. (except instead of int L, int W, replace it with pre-declared variables L and W without int in front of it.)
the following proposed code:
cleanly compiles.
properly prototypes the sub functions.
properly declares the sub functions.
eliminates most commentary that is just a repeat of the code.
Uses appropriate vertical spacing (between code blocks, between functions, between code activities).
fails to check the returned value from system functions (I.E. scanf()).
Follows the axiom: only one statement per line and (at most) one variable declaration per statement.
respects the right boundary of a printed output of the listing.
properly writes a 'float' literal
and now the proposed code:
#include "stdio.h"
// prototypes
int area (int, int);
float cookTime (float);
int main(void)
{
int funcnum;
printf("Welcome \n");
printf("Please enter a number\n");
scanf("%i",&funcnum);
switch(funcnum)
{
case 1:
printf("You entered 1."
" This is now the Turkey Time function.\n");
float weight;
printf("Welcome to the turkey timer...\n");
printf("Please enter a turkey weight \n");
scanf("%f",&weight);
float cTim = cookTime (weight);
printf("Cooking time is %.1f minutes.\n\n",cTim);
printf("\tThank you for choosing the MaiCorp Timing System, don't forget the gravy! \n");
break;
case 2:
printf("You entered 2."
" This is now the Area function.\n");
int len;
int wid;
printf("Welcome to the rectangle area calculator...\n");
printf("Please enter a length\n");
scanf("%i",&len);
printf("Please enter a width\n");
scanf("%i",&wid);
int ans = area (len,wid);
printf("Area is %i.\n",ans);
break;
default:
printf("You did not enter 1 or 2,"
" meaning that you are not running"
" a function this time.\n");
break;
}
return 0;
} // end function: main
int area (int L, int W)
{
int ans = L*W;
return ans;
} // end function: area
float cookTime (float w)
{
float cTim = w*15.0f; // << note the proper 'float' literal
return cTim;
} // end function: cookTime
I define a function finding the mean value of an array of int, the function is as follows:
float MeanInt(int x[],int num){
float mean, sum = 0.0f,res=0.0f;
int i;
for(i=0;i<num;i++){
sum += (float)(x[i]);
printf("x[%d] is %d\n", i,x[i]);
printf("sum is %f\n", sum);
}
res = sum/((float)(num));
printf("mean should be %f\n", res);
return res;
}
the printf() within this function all works correctly.
The problem is that when I use it in my project, like follows:
printf("mean number is %f\n", MeanInt(ls_tr_acl,num_round));
I meet with an error saying that:
format %f expects argument of type double, but argument 2 has type int
I'm fully confused because the printf() within the function MeanInt() print out exactly the correct result. I also test MeanInt() on some toy examples and it always works correctly. The problem only happens when I run it in my project.
You are not declaring the function MeanInt before its first invocation so compiler assumes the type of MeanInt is a function returning int taking any number of arguments.
FixInclude appropriate header file (containing the declaration), or move the definition above usage or declare it before usage as:
float MeanInt(int x[],int num);
You can declare it at global scope at the top of the file or in narrower scope also.
As I am new to programming, I was trying to write a simple code using functions which will give me the addition of three numbers. Here's the code!
/* Your includes go here */
#include <stdio.h>
int addThreeNumbers(int a, int b, int c)
{
int d;
d = a + b + c;
return(d);
/* Complete this function only
DO NOT write main function.
*/
}
int main()
{
int x, y, z, sum;
printf("Enter the three numbers: ");
scanf(" %d %d %d", &x, &y, &z);
sum = addThreeNumbers(x, y, z);
printf("The sum is %d", sum);
return 0;
}
And the error was as follows:
solution.c:30:5: error: redefinition of ‘main’
solution.c:15:9: note: previous definition of ‘main’ was here
You have another main function in the code somewhere. Post the complete code and I will take a closer look. But that is the only way you can receive this error
In modern C, empty argument parentheses mean that the type and number of arguments is unknown.
Although this segment runs fine with most compilers, yours might be picky. Try declaring main with zero arguments explicitly, like this:
int main(void) {
//code
}
Pretty sure this is one of the online coding sites' question. They put in the main function themselves by appending it to the code, you don't have to explicitly write it. Delete the main function you have written and check if that works out.
I am writing a program that calculates the square of two values (I must use a function.) I am sure that there are many mistakes but, I just can't seem to pick them out:
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int integer1, integer2, total = 0;
int squared(int integer1, int integer2);
int main(void)
{
printf("Enter two numbers to be Squared\n");
scanf("%d%d",&integer1,&integer2);
printf("Square of entered numbers = %d\n", squared(integer1,integer2));
return 0;
}
int squared(int integer1, int integer2)
{
int total;
total = integer1 + integer2;
return total *= total;
}
Header file:
#ifndef HEADER_H
#define HEADER_H
#define squared
int squared(int integer1, int integer2);
#endif
While you don't really need to specify the type int for the arguments that the function squared takes, because int is assumed whenever type is not specified, it is never bad to just put them down, as in:
int squared(int integer1, int integer2, int total);
// instead of
// int squared(integer1, integer2, total);
// both at the prototype and the definition of the function
Then again, you may just leave that out.
There are real problems in your function squared's definition. You aren't using semicolons ;, and you have written a return for the first statement, where I think you don't really want to return anything yet. You probably just wanted:
int squared(int integer1, int integer2, int total)
{
total = integer1 + integer2;
return total *= total;
}
One another important thing is, you are giving 2 less arguments to the squared function call from your main function. squared awaits for 3, you give it just 1. You probably wanted to call it as following:
...
printf("Square of entered numbers = %d\n", squared(integer1, integer2, total));
...
Lastly, you shouldn't be using variables that you haven't given a value to. integer1 hopefully will have a value assigned, integer2 also, hopefully. But total won't be assigned a value by the time you call the squared from main. You can just initialize it with a 0 or something, like this:
...
int integer1, integer2, total = 0;
...
Actually, you don't even need to have a total inside main, your squared function doesn't need a 3rd argument that holds total, as soon as you just declare an int total inside squared. But I won't get to that...
The main issue throughout is that you don't specify the type of each function parameter. You need to tell the compiler that integer1 is an int, for example. Also, see haccks' answer.
Two return statements one after the other are useless. The second return statement is unreachable. And you missed semicolons at the end of both the lines. May be this is the function you wanted:
int squared(int integer1,int integer2,int total)
{
total = integer2+integer2;
return total*total;
}
This calculates the sum of the two values and returns the square of the sum.
in addition to the function definition you need to change even the function call,
printf("Square of entered numbers = %d\n",squared(total));
to
printf("Square of entered numbers = %d\n",squared(integer1,integer2,total));
so that function call gets the value to add. read some basic c programs to know the format and syntax.
With all above answers, you seem to have missed ; in the return statement of your function.