Programming with functions using C. The functions are not executed - c

I'm learning C and doing the exercise of the function chapter. So i have written a small programm with 3 files and two small functions. Sincerly it does not work. I have no errors, the functions are simply not executed and i don't know why.
First of all this is my headerfile which only declares my functions.
//employee.h
int addEmployee(void);
int printEmployee(int i);
So the next file is for the definition of the functions.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int numE;
int i;
int addEmployee(void)
{
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
return i;
}
int printEmployee(int i)
{
printf("%d", i);
getchar();
getchar();
return i;
}
And the last file is used to execute the functions.
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}

Using
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
you're basically declaring 2 new functions with 0 arguments.
You're not calling your "old" functions.
This should work, as others have pointed out:
int main ()
{
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Because you're calling addEmployee(), storing it's result to emp and then printing emp using printEmployee. Since printEmployee is declared with one parameter, you just put emp in and it will work.

When you call a function you do not put the return type in front of the call. The call is simply the name of the function and any parameters you are calling it with. So your main function should look like this:
int main() {
addEmployee();
printEmployee(1);
return 0;
}
EDIT: So in your employee.c file, you are trying to use addEmployee() to take a number of employees from the command line and store it in the variable i right? And you want printEmployee() to tell you how many employees were entered? Here's how you would do that.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int i;
int addEmployee(void)
{
int numE;
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
}
int printEmployee()
{
printf("%d", i);
getchar();
getchar();
}
Here's what I did.
First, I made numE a variable local to the addEmployee function that uses it. Generally you should keep variable scope as small as possible. That means keep them down to the lowest level they are used. In this case, numE is only needed by addEmployee() so that's its scope.
Second, I removed the parameter from int printEmployee(int i). It was overriding your i variable at the file level. So you were storing the number read into numE in i but then when you entered printEmployee() you were creating a new, empty i that hid it. When you called printEmployee(1) from main, you were passing the value 1 into i in printEmployee(int i). By removing the parameter, you stop hiding employee.c's i.
Finally, I removed the returns. A function doesn't have to return anything in C. And if you are not going to use the return, then it's just an extra line of code to include it.
There's one more change you'll have to make to make this work, in your lab6.c file. Remove the parameter from the call to printEmployee()
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
addEmployee();
printEmployee();
return 0;
}
Should work the way you expect it now.

you want:
int main ()
{
addEmployee();
printEmployee(1);
return 0;
}

Change this:
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
To this:
int main ()
{
addEmployee();
printEmployee();
return 0;
}
You're re-declaring the functions instead of calling them.
You'll also have to change your printEmployee function to not accept an integer argument; it seems like it should just be using the same global variable as addEmployee. This is a bad idea though; global variables are generally to be avoided. addEmployee should probably return the employee ID, which you could store and then pass into printEmployee.

Related

How to put a function as an argument in C?

I would like to execute a function given in the paramater of a function. Let me explain with an example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int object() {
printf("Hello, World!");
return 0;
}
int run_func( int a_lambda_function() ) {
a_lambda_function();
return 0;
}
int main() {
run_func( object() );
return 0;
}
Now, I want to run "object()" in the parameters of "run_func(int a_lambda_function()").
When I run it, It returns an error. How would I achieve this is full C?
Restrictions I have:
Absolutly No C++ allowed.
Functions can be passed as arguments or stored into variables as function pointers.
The definition for a function pointer compatible with your object function is int (*funcp)() ie: a pointer to a function taking an unspecified number of arguments and returning int.
In modern C, functions with an unspecified number of arguments are not used anymore, and functions taking no arguments must be declared with a (void) argument list.
Here is a modified version:
#include <stdio.h>
int object(void) {
printf("Hello, World!");
return 0;
}
int run_func(int (*a_lambda_function)(void)) {
return a_lambda_function(); // can also write (*a_lambda_function)()
}
int main() {
return run_func(object);
}

C - Scanf straight into an function argument?

So, if I have the function foo:
float foo(float a, float b){
return a*b;
}
and I call it from another function, how can I call it like this?
void main(){
foo(scanf("%d"), scanf("%d");
}
scanf doesn't return the input string, I don't want to create a bunch of temp variables. Is that possible, and if so how?
You can't directly return a value from scanf. But you can create a function yourself that returns a value from scanf, but it'll still use temp variables inside of it:
int getInteger() {
int input;
scanf("%d", &input);
return input;
}
Then you can use it like:
foo(getInteger(),getInteger());
However, if you really don't wanna use variables, you can just use get_int() from cs50 library. More info here.
#include <cs50.h> // include cs50 to use get_int
int main(void)
{
foo(get_int("Number 1: "),get_int("Number 2:"));
return 0;
}

Header files and functions, is my function, parameters, or header prototype?

I just started with C and am tasked with using a header to house a prototype for a function. The problem is that nothing happens when I'm expecting a prompt for input. I didn't get an error and would like to know where to look at first to solve my problem. This is what I have so far.
LAB2.c
#include <stdio.h>
#include "LAB2HEADER.h"
int main(){
double *p;
double array [10];
p = array;
const int size = 10;
void input(p,size);
return 0;
}
LAB2HEADER.h
#ifndef LAB2HEADER_H_
#define LAB2HEADER_H_
void input (double *array,const int size);
#endif
LAB2HEADER.c
#include <stdio.h>
#include "LAB2HEADER.h"
void input (double *array,const int size){
for (int i = 0; i < size ; i++)
{
printf("Input a value");
scanf("%lf", &array[i]);
}
}
A lot of the notes I look at seem to only either use Int as a parameter or have a function with no needed parameters, could my mistake be in my array pointer is it a problem with the way I made my function?
void input(p,size);
This line makes no sense. If this is supposed to be a function call, you need to remove void.
Also, since your print statement does not end with a newline, nor do you flush stdout before reading in the value, your prompt might still be in the output buffer and not be output until you hit the newline AFTER entering the value.

why does the compiler give a warning for unused function?

I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.
Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.
You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error

Programming with functions and structures using C, getting strange output, no errors

I'm learning a bit C and i'm doing an exercise where i use structures and functions to collect employee infos and just print them out.
I'm declaring the functions and the struct in the header since i need them in both of the other files.
//employee.h
int addEmployee(void);
int printEmployee(int i);
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
The "core" file is executing the both functions. The first function asks for the number of employees and gives a value back for the second function where the information is collected and stored. There are no errors and i've checked the code several times.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int numE;
int i;
int addEmployee(void)
{
struct employeelist employee[5];
int numE;
printf("How many employees do you want to add to the list?: ");
scanf("%d", &numE);
printf("Please type in the last name, the first name,\nthe personal number and the salary of your employees.\n");
for (i=0; i < numE; i++)
{
printf("Last name: ");
scanf("%s", employee[i].last);
printf("First name: ");
scanf("%s", employee[i].first);
printf("Personal number: ");
scanf("%d", &employee[i].pnumber);
printf("Salary: ");
scanf("%d", &employee[i].salary);
}
return numE;
}
int printEmployee(int emp)
{
struct employeelist employee[5];
for (i=0; i < emp; i++)
{
printf("Last name: {%s}\nFirst name: {%s}\nPersonal number: {%d}\nSalary: {%d}\n",employee[i].last,employee[i].first, employee[i].pnumber, employee[i].salary);
}
getchar();
getchar();
return emp;
}
The last file contains the main() function to execute the functions above.
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int emp;
int main ()
{
struct employeelist employee[5];
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Now my problem is that everything works only the output is incorrect. I can't even say what it is. Some kind of random mix of signs, letters and numbers. Since i have no idea where my mistake is, i would be glad about any advise to solve this problem. Thank you.
I have added a screenshot of my output. Maybe it helps.
You're trying to use a local variable, which ceases to exist when the function returns.
int addEmployee(void)
{
struct employeelist employee[5];
/* ... */
}
The variable employee only exists inside the addEmployee() function; and it is a different object every time the function is called.
int printEmployee(int emp)
{
struct employeelist employee[5];
/* ... */
}
This employee has no relation to the one in addEmployee.
But don't do the easy thing now (*); do the right thing: declare the array in the main() function and pass it around.
//employee.h
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
/* add up to `maxemp` employees to the array and
** return number of employees added */
int addEmployee(struct employeelist *, int maxemp);
/* print all employees from index 0 to (nemp - 1) */
int printEmployee(struct employeelist *, int nemp);
Declare an array in main(), and pass it around
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main ()
{
int emp;
struct employeelist employee[5];
int emp = addEmployee(employee, 5);
printEmployee(employee, emp);
return 0;
}
(*) Don't declare a global variable for employees
Edited employee.h and added a main() function
You have a brand new variable in your print function that isn't even initialized. So it contains only garbage and that is printed
The heart of the problem is that you're working with three different arrays of employees instead of the one array that you think you've got. Anything declared within a pair of curly braces in C only 'exists' while the program is executing code inside those braces. You've declared three different arrays of employee structs in three different blocks of code.
To point you in the right direction (irrespective of whether this is homework or self-study, this is a learning exercise so just fixing your code probably isn't what you want) you should think about how you can pass the same employee array to each of your functions in turn. (EDIT: pmg beat me to it.)
Declare the array once, in your main() function as you've already done, and modify your two functions printEmployee() and addEmployee() to take that array as a parameter instead of declaring their own local arrays.
Here is a very simple example using ints showing how parameters and return values work. You'll have to do some reading about pointers to extend this to your case.
int main() {
int number = 2;
int newNumber;
newNumber = timesTwo(number);
printf("number: %d newNumber: %d", number, newNumber);
}
int timesTwo(int param) {
return param * 2;
}
Before you start breaking things out into separate files and working with structs and pointers it is a good idea to practice the concepts of functions, parameters and variables by building simple programs in a single file.
You declare the employee array locally to both functions, so they cannot access each other's data.
The main issue, as others have already said, is that you are declaring a struct employeelist employee[5] in each of your functions. This makes those variables local to their functions and thus inaccessable from one function to the other. So, when printEmployee goes to print, the data it is printing is gibberish.
There are a few things needed to fix this:
Make one declaration of your employee list in your main (which you already have) and then pass that into the functions. You'll need to do the passing by means of the array name so that the functions will treat the array properly.
As a result of the above, you'll need to move the struct declaration to be above the function prototypes and then change the prototypes in employee.h to accomodate the passing of the employeelist.
You'll have to check that the user doesn't try to enter more records than your array has space for. Alternatively, you could just declare a pointer in the main and malloc() the needed memory in the addEmployee function.
A few other suggestions to make things a little easier on yourself:
Call your struct employee (or something like that) and your array employeelist (or something similar).
Use typedef on your struct to shorten & simplify your declarations.
Change your printEmployee to be a void function (i.e. void return type).
Take a look.. Well distribued and simple to read, it just needs a little improvement to become bigger and do the work u want.
typedef struct
{
char last [20];
char first[20];
long int pnumber;
int salary;
}employee;
/* the two functions clearly declared */
int addEmployee(employee const wEmployeeList[]);
void printEmployee( employee const wEmployeeList[], int );
int main()
{
int numberE;
employee employeeList[2];
numberE = addEmployee(employeeList);
printEmployee(employeeList, numberE);
return 0;
}
int addEmployee(employee const wEmployeeList[2]){
int i;
for (i=0; i < 2; i++)
{
printf("Last name: ");
scanf("%s", wEmployeeList[i].last);
printf("First name: ");
scanf("%s", wEmployeeList[i].first);
printf("Personal number: ");
scanf("%ld", &wEmployeeList[i].pnumber);
printf("Salary: ");
scanf("%d", &wEmployeeList[i].salary);
}
return 2;
}
void printEmployee(employee const wEmployeeList[2], int numberEmployee){
int i;
for (i=0; i < numberEmployee; i++)
{
printf("\n\nLast name: %s\nFirst name: %s\nPersonal number: {%ld}\nSalary: {%d}\n \n",wEmployeeList[i].last,wEmployeeList[i].first, wEmployeeList[i].pnumber, wEmployeeList[i].salary);
}
}

Resources