The definition of a function in C - c

I have an assignment question which ask me about the definition of a function. I'm not quite sure how it want me to answer. The question is below:
Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m

Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m
Lets try to unwrap this, there are no real-type in C so Real is the code word for float or double. Function is the name of a subroutine.
The wording of the question is vague definition could ask for the optional prototype declaration(the definition of functions which is usually stored in the header files) which is
float multiplier(float,float);
or the function could be defined and implemented at the same time
float multiplier(float n, float m){
return (n*m);
}

Your question is,
Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m
A function is a certain way to write a code, that way you can call it in the main, or wherever, and it performs any tasks assign to it. In your case, for your multiplier, it will perform the function of multiplication. Therefore, it would make sense to use two integers in order to perform this task.
To start, since we will be returning an int, we will call it as that. We set it up like this,
type name (*parameters)
{
}
in your case,
int multiplier(Parameters go here)
For the code:
int multiplier(int m, int n)
{
return m*n;
}
then when we call it in the main, we would pass two numbers for the multiplier and it will return it as a product.
int main()
{
multipler(2, 4); // prints 8
}
I hope this helps, I tried to explain it very basic.

Related

callback function confusion in general

I am very confused about callback function. Specifically I am confused about the order of the functions being called in the sequence of functions that make use of callback functions.
For example, I have this piece of code and problem in a question that I recently done, and the solution is below:
The procedure nthPrime shown below computes the nth prime number asynchronously; i.e., it returns
immediately and then calls callback sometime later with the value of the requested prime number. Give
code below that uses this procedure to print the product of the 100th and 200th prime numbers without spinwaiting
or polling (i.e., your code must call this procedure twice and multiply the results). You can use global
variables in your solution if you like.
void nthPrime(int n, void (*callback)(int));
So the solution is:
int t;
void nthPrime(int n, void (*callback)(int));
void foo(int n) {
nthPrime(100, a);
}
void a(int p) {
t = p; // why assign p to t here?
nthPrime(200, b);
}
void b(int p) {
printf("%d\n", t * p); // t*p, but what is p here?
}
However I am totally confused about how the solution (or functions above is being used to implement the request to print the product of the 2 primes).
I guess foo() is being called first. Then I am kind of lost how the sequences is being called (I know some functions return right-away and wait for the result of the "call-back" function to finish???). I am confused what is being returned right away, and what will be run in a near future to return something later in the sequences.
When you call nthPrime(100, a);, nthPrime will calculate the 100th prime, and then call the a function.
When it calls a, p will be that 100th prime.
a then calls nthPrime(200, b);. nthPrime will calculate the 200th prime, then call the b function.
When it calls b, its local variable p will be that 200th prime.
b needs to multiply the prime that it received by the 100th prime that was received by a. It's not possible to access variables in another function's scope directly. That's why a copies its parameter to the global variable t -- this provides the communication between the two callback functions.
In many other languages this would be done with closures rather than global variables, but C doesn't have closures. This limits the flexibility and capability of callbacks in C.

Manipulating C function

Is there exist a way to manipulate C function some how
for eg - we know C printf() function return Number of character printed to the console.
So is there any way that i can get number of character but not letting printf() function print to console. using same printf() from stdio.h
I know return is the last statement to get executed in a function hence what i am asking may be impossible but i do want to hear from the community i.e is my hypothesis i.e manipulating c function is possible or not?
If you have access to the source code and you're able to recompile it with your changes, then sure, you can do it. Consider this:
int foo(int a, int b)
{
int c = 4;
int d = 8;
int f = c * a;
int g = d * b;
int h = f + g;
return h;
}
If you want the value stored in f, there are a couple of ways to do it: 1) you peak into the stack with inline assembly (non-portable, non-reliable), 2) you change the code to expose the variable. Notes on "peaking the stack": what if the architecture does not have a stack? What if the values are all on registers? What if the compiler optimized all the function calls to inline calls? What if...?
Because if you look at the function from the outside, all the function is... is this:
int foo(int a, int b);
You can get an integer from it if you pass two integers to it as arguments. That's all you can do with the API. There is no way in C you can get the value of f or g.
In the analogy, f and g are printf's internal state, and you can not access it. Functions are designed to work as perfect black boxes: it gives you an output based on your input, but how it does it doesn't matter.

Variable Initialization in Function

I'm fairly new to coding and am currently learning C. In my C programming class, my instructor gave us the assignment of writing a program that uses a function which inputs five integers and prints the largest. The program is fairly simple even for me, but I'm facing some problems and was hoping to get some advice.
#include <stdio.h>
int largest(int x);
int main(void) {
int integer1;
largest(integer1);
return 0;
}
int largest(int x) {
int i;
for (i = 0; i < 5; i++) {
printf("Enter an integer: ");
scanf_s("%d", &x);
}
return x;
}
This is the code that I have written. The main problem that I am having is that in my main method, the IDE tells me to initialize the value of integer1. However, I'm not really sure how to do that because I'm supposed to input the value within the largest() method via the scanf_s function. How may I solve this?
The problem is here, the warning message is to warn you about the potential pitfall of using the value of an uninitialized automatic local variable. You made the call like
largest(integer1);
but you ignore the return value, so the integer1 remains uninitialized.
Remember, in view of largest(), x is a local copy of the actual argument passed to that function, any changes made to x won't be reflecting to the caller.
That said, your code is nowhere near your requirement, sorry to say. A brief idea to get there would be
Create a function.
Create a variable (say, result) and initialize with minimum possible integer value, INT_MIN
Loop over 5 times, take user input, compare to the result value, if entered value found greater, store that into result, continue otherwise.
return result.
I know that normally help for assignments shouldn't be given but I have to say that you might need to rethink what you want to do.
You are inputting an integer to the function named largest. But why are you only inputting a single integer to a function that should return the largest value. You can't do much with a single number in that case.
You should instead be inputting say an array of 5 values(as said in your assignment) to the function and let it return the largest.
The order would then be:
Read 5 values and save to an array
Call the function largest with the array as input
Let the function do it's work and return the largest value
Do what ever you want with the largest value
But if you only want to remove the warning simply type
int integer1 = 0;

Using It's Own Call as One The Parameters in a Function call statement

Here Is my code:
#include <stdio.h>
int mul(int,int);
int main()
{
int sum,m,n;
scanf("%d%d",&m,&n);
sum=mul(10,mul(m,n));
printf("%d",sum);
}
int mul(int x,int y)
{
int sum;
sum=x+y;
return(sum);
}
Input
10
5
Output
25
Can someone tell me why I get 25 as output? Was the function called 2 times?
One during parameters and other time during sum?
It's perfectly simple:
sum=mul(10,mul(m,n));
You're calling mul() with 10 as the first argument, and the return value of mul(m, n) as the second argument.
m and n are 10 and 5, so mul(10, 5) returns 15. The statement in your main function then evaluates to this:
sum = mul(10, 15);
Which is 25.
TL;DR: yes, mul() is called twice. Once with m and n as arguments. The second time with the sum of m and n, adding 10
Using a debugger, or even looking at the assembler output generated by the compiler would've told you there were 2 successive calls to mul.
And yes, as others have rightfully pointed out: reading the help section (in particular how to ask) would be a good idea. It explains that you're expected to do the sensible debugging/diagnostic steps yourself. Only if that didn't solve the problem should you post a question here:
Explain how you encountered the problem you're trying to solve, and any difficulties that have prevented you from solving it yourself.
You merely state that, given input X, you get output Y, and you don't know why.

How does a forward declaration work?

I understand declaring factorial before main. But how can main calculate the answer when the factorial formula comes after it?
#include <stdio.h>
long long factorial(int);
int main()
{
int n;
long long f;
printf("Enter a number and I will return you its factorial:\n");
scanf_s("%d", &n);
if (n < 0)
printf("No negative numbers allowed!\n"); //prevent negative numbers
else
{
f = factorial(n);
printf("The factorial of %d is %ld\n", n, f);
}
return 0;
}
long long factorial(int n)
{
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
But how can main calculate the answer when the factorial formula comes after it?
First thing — main does not calculate the answer; it's your factorial function which does it for you. Also there are 3 steps which I feel you need to know about when writing programs:
You write the code in a file.
You compile the file and the compiler checks for syntactical mistakes, no code calculation is happening in this phase its just mere lexical analysis.
Then linking takes place later. If you receive a linker error, it means that your code compiles fine, but that some function or library that is needed cannot be found. This occurs in what we call the linking stage and will prevent an executable from being generated. Many compilers do both the compiling and this linking stage.
Then when you actually run your code — it's then when the code's control flow goes into the factorial function when the calculation happens, i.e. at runtime. Use a Debugger to see this.
The below image is taken from Compiling, Linking and Building C/C++ Applications
From Wiki:
In computer programming, a forward declaration is a declaration of an
identifier (denoting an entity such as a type, a variable, a constant,
or a function) for which the programmer has not yet given a complete
definition....
This is particularly useful for one-pass compilers and separate
compilation. Forward declaration is used in languages that require
declaration before use; it is necessary for mutual recursion in such
languages, as it is impossible to define such functions (or data
structures) without a forward reference in one definition: one of the
functions (respectively, data structures) must be defined first. It is
also useful to allow flexible code organization, for example if one
wishes to place the main body at the top, and called functions below
it.
So basically the main function does not at all need to know how factorial works.
But how can main calculate the answer when the factorial formula comes after it?
The order in which a C program executes is only partially determined by the order in which the text appears.
For instance, look at the printf function you are using. That doesn't appear in your program at all; it is in a library which is linked to your program.
The forward declaration makes it known (from that point in the translation unit) that there is expected to exist such and such a function having a certain name, arguments and return value.
The simple answer is that your C program is processed from beginning to end before it begins to execute. So by the time main is called, the factorial function has already been seen and processed by the C compiler.
An address is assigned to the compiled factorial function, and that address is "backpatched" into the compiled main function when the program is linked.
The reason forward declarations are needed at all is that C is an old-fashioned language originally designed to allow one-pass compilation. This means that the compiler "translates as it goes": functions earlier in a translation unit are compiled and emitted before later functions are seen. To correctly compile a call to a function which appears later (or, generally, appears elsewhere, like in another translation unit), some information must be announced about that function so that it is known at that point.
It works in this manner: let's take an example to find factorial of 3
Recursion :
As factorial of 0 is 1 and factorial of 1 is also 1, so you can write like
if(n <= 1)
return 1;
Since in main function when compiler sees this f = factorial(n); function, the compiler has no idea of what it means. it doesn't know where the function being defined, but it does know the argument the function is receiving is correct, because it's a user defined function that has its definition after main function.
Hence there should be some way to tell the compiler that I am using a function with name factorial which returns long long with a single int argument; therefore you define a prototype of the function before main().
Whenever you call the function factorial the compiler cross checks with the function prototype and ensures correct function call.
A function prototype is not required if you define the function before main.
Example case where function prototyping is not required :
/*function prototyping is not required*/
long long factorial(int n)
{
//body of factorial
}
int main()
{
...
f=factorial(n);
...
}
Here, the compiler knows the definition of factorial; it knows the return type, the argument type, and the function name as well, before it is called in main.

Resources