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.
Related
Before i start, I am not good at English so I use a translator, so you may not understand well.
I'm so sorry. But the content of the question is easy, so there is probably no difficulty understanding.
One day I don't remember very well, but I saw a code similar to the one below.
#include <stdio.h>
int main(){
int a,b,c = 1,d,e;
return 0;
}
At that time, I just let it go. But now that I think about it, I'm curious.
So I checked the value of C, and it was printed 1.
And I changed 1 to 0 and confirmed that the value of C was zero.
This result was the same for the other numbers.
I've never seen a code like this before.
In the meantime, I knew that to declare a number of variables, I would have to do as the code below.
int a = 1, b = 2, c = 3;
But it wasn't what I knew.
After several experiments, I found that a,b,c,d,e were independent variables.
Except for C, a,b,d,e contained garbage value.
I wonder why this is grammatically possible and why the values are not allocated in order from left to right.
Once again, I'm sorry for using the translator.
int a,b,c = 1,d,e;
is the same as
int a;
int b;
int c = 1;
int d;
int e;
Except for C, a,b,d,e contained garbage value - This is because only C is both declared and initialized with the value 1. Others are just declared in a random memory location, hence has garbage values
I wonder why this is grammatically possible - It is a right syntax still. See the answer by #pmg
In the meantime, I knew that to declare a number of variables, I would have to do as the code below. int a = 1, b = 2, c = 3; - Here you are actually declaring as well as initializing them with different values. You can always declare any number of variables (of the same datatype) in a single statement.
How could I achieve something like this ...
int main(void)
{
if (f(x) == (a || b))
{
puts("Success");
}
return (0);
}
This would print Success if the return of f(x) is equal to a or b.
I know it is possible to store it in a variable but my question is:
"Could something like this be done by calling the f(x) function only once without using a variable?"
Edit 1: I'm not allowed to use the switch statement for this assignment
Edit 2: Could I set a range with only one expression like this?
if ( 2 < f(x) < 5)
Would this be valid (return type is int)?
how to test for multiple return values from a function called once without storing into a variable (?)
Not really, but with some restrictions let us abuse C and assume a, b and f() return a character.
1Form a character array made up of a and b and search it using memchr(). Inspired by #David C. Rankin (It does not store the result of f() in a variable, but does call a function)
int main(void) {
// v-------------v compound literal
if (memchr((char [2]){a,b}, f(x), 2)) {
puts("Success");
}
return 0;
}
I see OP added "return type is int" - Oh well.
if ( 2 < f(x) < 5) is valid code, but is does not do what OP wants.
It is like if ( (2 < f(x)) < 5) which compares f(x) with 2 and results in 0 or 1, which is always less than 5.
Tough crowd tonight, so how about the below. Needs a bit of extension math for int overflow`, but is close.
abs(2*f(x) - (a+b)) == abs(a-b)
1 Not serious code suggestions for production code - use a temporary.
This can obviously be done using a switch statement. Another way would be calling a function returning true or false with the first function value as input, another way could be a jump table or even > or bit checking using binary operators depending on a and b values (very common for testing multiple bit flags at once).
But really you shouldn't care about using or not using a variable in such cases. Current compilers are quite good putting temporary variables like that in registers.
EDIT: given the constraints, the most likely solution is using some bit fu, but it fully depends of values of a and b and c, etc. The common way is using powers of two as values to check. Then you can check a set of values in only one operation.
exemple: a = 1, b = 2, c = 4
if (f(x) & (1+2+4)) {...}
checks if we have a or b or c or a superposition of these values.
C language does not such constructs. You need do save the result of the function or/and both a & b.
Of course you can:
int compare(int a, int b, int f)
{
if(a == f || b == f) { puts("Success"); return 0;}
return -1;
}
int f(int x)
{
return x * x;;
}
int main()
{
compare(5,8,f(3));
}
but of course it saves all the values as the functions parameters.
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.
I have one question:
int swapnum( int x, int y )
{
int tempnum ;
tempnum = x ;
x = y ;
y = tempnum ;
return tempnum;
}
int swapnum(int, int);
int main( )
{
int x = 35, y = 45 ;
printf("Before swapping: %d, %d", x, y);
swapnum(x, y);
printf("\nAfter swapping: %d, %d", x, y);
return 0;
}
I have found this example in internet which demonstrates how call by value works. I understand everything except one thing. For what do we need call by value if we do not get changed result in main? I understood idea of call by reference; we will receive changed result but for what do we need call by value if result is changed only locally (in upper part of this code) and main stays unchanged (printf("\nAfter swapping: %d, %d", x, y);)? And if you write your example too to demonstrate it would be great.
There are even functions which do not return anything.
They have a prototype like
void useTwoNums(int, int);
They illustrate even better than your example that it is not necessary to return anything, even less something which somehow uses the two input parameters and/or depends on them.
The concept which you seem to be missing is the difference between "functions" in mathematical context and "functions" in programming. In programming a function might well do something without returning something. One example is a function which just nicely prints the input values, compare printf(),
http://en.cppreference.com/w/c/io/fprintf
Its return value can be handled inside the return-value-free function to illustrate.
The extreme case would be a function with neither parameters nor return value:
void DoSomethingInFreespace(void);. Functions like that can achieve the data to process e.g. via other input channels. Or they are simply refactored pieces of code, e.g. for reuse, which have a sufficiently rich context, e.g. global or file local variables.
To make the answer more complete, I will integrate some points from comments (including the one by OP, which focuses on return values):
With call-by-value functions are more close to mathematical functions, and are then much more easily composed. (Jean-Baptiste Yunès).
and
it allows you to send values without worrying that some function will change them. It's very convenient. (njzk2)
Both (and other, too) stress that a mathematical function does not alter the parameters; this is something of a "promise" which programmers appreciate.
Turning it around:
when using call by value if you want that [a value in the context outside of the function, e.g.] main be changed we must return the result (OP)
Different angle:
when using call by reference, we don't need to return; it [the parameter] itself changes [outside of the context of the called function and can be used as a] result (OP)
I have found this example in internet which demonstrates how works call by value. I understand everything except one thing: for what do we need call by value?
You don't need call-by-value. But call-by-value is how C works, and most programming languages actually, so you would do well to learn it.
I understood idea of call by reference, we will receive changed result but for what do we need call by value if result is changed only locally
Call-by-value is used in most programming languages because it makes it easier to think about the code. When you see doStuff(x, y); you know that x and y won't change. They can only change if you write doStuff(&x, &y); or x = doStuff(y); or something like that. You don't need go and look up the DoStuff Manual to find out whether doStuff is supposed to change them.
and if you write your example too to demonstrate it would be great.
There's really nothing to demonstrate; the point of call-by-value is that nothing happens. Do you want a demonstration of nothing happening?
The return value is useful when you have formulas.
If you want to calculate the hypotenus from the cathetus and you pass the value of the latters, you do not want theit value modified.
i am a beginner in C programming, and while making a program i wondered if there can be a universal input function input(); be made, such that the variable name given in braces be asked for input like this:
input(a);
result:
enter value of a: 10
now (after the input) if i write like this in any program like:
#include<stdio.h>
main()
{
int a;
float b;
char c;
input (a);
printf("value of a = %d\n",a); // 1
input(b);
input(c);
printf("value of b = %f\n",b); // 2
printf("c = %c\n",c); // 3
}
then output should be like this:
output:
enter value of a: 10
***value of a = 10***
enter value of b: 10.0
enter value of c: D
***value of b = 10.000000***
***c = D***
i.e the function parameter should take values acording to the type of variable concerned(like char,float,int etc) like if a were char then value entered in a would be saved accordingly.
i thought to implement it using structures but i am not able to think, how to link the actual parameter passsed in input(); with the struct members
update: i have written the lines 1,2,and 3(in comments: the printf() functions) just to show that the values of a,b, and c are aptly/rightfully stored in their corresponding types
With literally the same syntax as you've written - no, you need C++ features for this (function overloading), but it worth knowing that internally it will just use set of different functions, so actually it's almost exactly the same as input_int, input_char, etc.
You could use union (probably union within a struct - you need to save actual type somewhere), but it's quite different approach.
Macros (especially C11 _Generic's, if you could use C11 features) could be good alternative too.