I was wondering if it is possible in C (89/90) to chain function calls, and where it is defined in the C spec. I assume this isn't possible since a google search reveals no mention of it.
I thought of this because of a related conversation with a friend of mine where he told me that given a function returning a struct, you cannot perform any operations on said struct within the same statement; instead, you have to assign the result of the function to a variable, and then manipulate the struct via the variable instead of directly from the function result itself. This leads me to believe that you can't chain functions either, but I can't seem to find these limitations discussed in the spec.
Edit : Sorry, I should have been specific on the return value. Assuming the function returns a function pointer, is it possible to dereference and call the result within the same statement, in fluent fashion?
For example, assuming getFunc returns a function pointer :
(*getFunc(getFuncParam))(otherFuncParam)
Or in the struct case, assuming a struct with an int member called count:
funcReturnsStruct(param).count++
Here's what function chaining looks like in C:
post_process(process(pre_process(data)));
Obviously, your friend is wrong. As long as the functions cooperate by accepting and returning the same type of value you can chain the calls all you like.
Contrast this with something like
data.pre_process().process().post_process();
The big difference is that in C (which has no encapsulation, hence no classes) functions have center stage while in more modern OO languages it's objects that get more attention.
Update: Sure it's possible to chain no matter what each function might return. For example:
int increase(int x) {
return x + 1;
}
typedef int (*increase_fp)(int);
increase_fp get_increase() {
return increase;
}
int main(void) {
printf("%d", get_increase()(1));
return 0;
}
See it in action.
a friend of mine where he told me that given a function returning a struct, you cannot perform any operations on said struct within the same statement
Your friend is correct in the sense that the return value of a function cannot be the target of an assignment (it's not an lvalue). IOW, you can't do something like
int foo(void) { int x = 5; return x; }
...
foo() = 6;
However, if the return type of a function is a struct or a union, you can apply the component selection operator to the return value, such as
int x = foo().memb;
Similarly, if the return type of the function is a pointer to a struct or a union, you can write
int x = foo()->memb;
And if the return value is a pointer to another function, you can call that other function like so:
int bar(int x) { ... }
int (*foo)(int x) { return bar; }
int x = foo(x)(y); // or (*foo(x))(y) -- the result of foo(x) is
// called with the argument y
although anyone who has to maintain or debug your code may beat you severely for it.
What you cannot do is something like
foo().memb= ...;
foo()->memb = ...;
which wouldn't make sense anyway, because the lifetime of the value returned by foo ends when the statement ends - you wouldn't be able to retrieve that modified value.
Your friend is wrong.
If we have:
struct Point3
{
float x, y, z;
};
const Point3 * point3_get_origin(void);
then you can certainly do:
printf("the origin's y coordinate is %f\n", point3_get_origin()->y);
The function returns a value of the given type, so the call of the function can be used wherever such a value is needed in an expression.
Do you mean something like this?
typedef void (*CALLBACK)(void);
CALLBACK getCallback();
void test()
{
getCallback()();
}
It compiles with no warning in GCC 4.6.1 (default std).
There's a much faster and easier way to answer this than posting here: try it.
#include <stdio.h>
struct s {
int a;
} s;
struct s * getS() {
s.a = 13;
return &s;
}
int main(int argc, char * const argv[]) {
printf("%d\n", getS()->a);
return 0;
}
% gcc test.c -o test -Wall -pedantic
% ./test
13
%
Not so much as a pedantic warning. Expected output. Looks like it's perfectly fine. However, as has been pointed out, it would be better to store the return value and check for errors.
Related
I am taking a hybrid class of "Algorithms, architecture, and assembly language" at my local community college. Although it's an intro class and mainly focuses on how computers turn code into binary, we have some assignments for C code. Some of the stuff we've never even gone over in class, and I'm lost.
The instructions read:
Write a function named DoSomething, with no return value, it should do just one (1) thing: multiply the global variable my_result by 5 and store the result back into my_result
You do not have to call DoSomething, or initialize my_result, I will do that.
I have tried
int my_result;
dosomething (my_result) {
my_result = my_result * 5;
}
but this is incorrect. I have almost zero experience with C language and am stuck. I'm not asking anyone to do my homework, I just want to understand. This has not been covered in class.
You almost have it. Since my_result is global, you do not need to pass it into the function, it is accessible everywhere. Oh, and every function needs its return value specified. Use void to specify that there is no return value and no parameters.
int my_result;
void dosomething (void) {
my_result = my_result * 5;
}
A correct function declaration must have a type, the name of the function and its arguments.
type function_name(type1 arg1, type2 arg2, type3 arg3, ...);
If a function does not return anything, then type must be void
void function_name(type1 arg1, type2 arg2, type3 arg3, ...);
If a function does not take any parameter, then the you can use void instead
of the list of arguements:
type function_name(void);
Your dosomething function is missing the return type, which should be void
(assignment says Write a function named DoSomething, with no return value)
and it takes no arguments (at least the assignment does not specify any), so the
correct prototype of the function must be:
void DoSomething(void);
So the correct program
#include <stdio.h>
int my_result;
void DoSomething(void)
{
my_result = my_result * 5;
}
int main(void)
{
my_result = 6; // initializing global variable
DoSomething();
printf("my_result: %d\n", my_result);
return 0;
}
which will print my_result: 30.
There is nothing to get worried about. Relax, it's just part of the process in becoming a good developer.
To solve such problems, first note what the function expects and we want from the function to return.
Now, in your question, it is given that function would return nothing. So the return type of the function would be void.
Now, since we have to use a global variable, it means function expects no argument.
Hence, our code is :
#include <stdio.h>
int my_result; // Our Global Variable
void doSomething (void) // Our Function
{
my_result = my_result * 5;
}
int main()
{
/* Asking the value of my_result */
printf("Please enter a value : ");
scanf("%d", my_result);
doSomething();
printf("\nNew value of my_result is : %d\n", my_result);
return 0;
}
// End of main.
The instructions read:
Write a function named DoSomething, with no return value,…
So code for that is:
void DoSomething(void)
… it should do just one (1) thing: Multiply the global variable my_result by 5 and store the result back into my_result.
And code for that is:
{
my_result = my_result * 5;
}
You do not have to call DoSomething, or initialize my_result, I will do that.
Done. The total code requested is:
void DoSomething(void)
{
my_result = my_result * 5;
}
You have indicated in your comments that you are submitting this code into some sort of automatic grading/checking software. So that software is designed to accept code that matches the assignment, no more and no less. Quite likely, it puts your code into a file and that compiles a source file that includes the former file with #include. That source file defines my_result and main, so your code should not, or it will cause compilation and/or link errors. You need to submit just the code requested in the instructions.
Notes about your code:
The instructions say to write a routine named DoSomething. You used dosomething. These are different in C; the case matters.
You declared the routine without specifying a return type. The instructions say the instruction has no return value, but that does not mean you should just omit any return type. You should explicitly say there is no return value by using void for the return type of the function, as in void DoSomething(…). (For historic reasons, if you omit the return type in a function declaration, it defaults to int. Letting the type default like that is old syntax and should be avoided.)
The instructions did not say whether the routine should take parameters. This is a shortcoming in the instructions. However, dosomething (my_result) is incorrect for two reasons. One, my_result is described as a global variable, not a parameter. Two, it is the wrong syntax for a parameter declaration. A parameter declaration must have a type, as in dosomething(int x). Since the routine needs no parameters, a proper declaration is void DoSomething(void). (Although there is some possibility the instructor intended void DoSomething(), but that would not generally be preferred.)
I'm not sure if the question has asked before, but I couldn't find any similar topics.
I'm struggeling with the following piece of code. The idea is to extend r any time later on without writing lots of if-else statements. The functions (func1, func2...) either take zero or one arguments.
void func1() {
puts("func1");
}
void func2(char *arg){
puts("func2");
printf("with arg %s\n", arg);
}
struct fcall {
char name[16];
void (*pfunc)();
};
int main() {
const struct fcall r[] = {
{"F1", func1},
{"F2", func2}
};
char param[] = "someval";
size_t nfunc = RSIZE(r); /* array size */
for(;nfunc-->0;) {
r[nfunc].pfunc(param);
}
return 0;
}
The code above assumes that all functions take the string argument, which is not the case. The prototype for the pointer function is declared without any datatype to prevent the incompatible pointer type warning.
Passing arguments to functions that do not take any parameters usually results in too few arguments. But in this case the compiler doesn't 'see' this ahead, which also let me to believe that no optimization is done to exclude these unused addresses from being pushed onto the stack. (I haven't looked at the actual assemble code).
It feels wrong someway and that's usually a recipe for buffer overflows or undefined behaviour. Would it be better to call functions without parameters separately? If so, how much damage could this do?
The way to do it is typedef a function with 1 argument, so the compiler could verify if you pass the correct number of arguments and that you do not pass something absolutely incompatible (e.g. a struct by value). And when you initialize your array, use this typedef to cast function types.
void func1(void) { ... }
void func2(char *arg) { ... }
void func3(int arg) { ... }
typedef uintptr_t param_t;
typedef void (*func_t)(param_t);
struct fcall {
char name[16];
func_t pfunc;
};
const struct fcall r[] = {
{"F1", (func_t) func1},
{"F2", (func_t) func2}
{"F3", (func_t) func3}
};
...
r[0].pfunc((param_t) "foo");
r[1].pfunc((param_t) "bar");
r[2].pfunc((param_t) 1000);
Here param_t is defined as uintpr_t. This is an integer type big enough to store a pointer value. For details see here: What is uintptr_t data type.
The caveat is that the calling conventions for param_t should be compatible with the function arguments you use. This is normally true for all integer and pointer types. The following sample is going to work, all the type conversions are compatible with each other in terms of calling conventions:
// No problem here.
void ptr_func(struct my_struct *ptr) {
...
}
...
struct my_struct struct_x;
((func_t) &ptr_func)((param_t) &struct_x);
But if you are going to pass a float or double argument, then it might not work as expected.
// There might be a problem here. Depending on the calling
// conventions the value might contain a complete garbage,
// as it might be taken from a floating point register that
// was not set on the call site.
void float_func(float value) {
...
}
...
float x = 1.0;
((func_t) &float_func)((param_t) x);
In this case you might need to define a function like this:
// Problem fixed, but only partially. Instead of garbage
// there might be rounding error after the conversions.
void float_func(param_t param) {
float value = (float) param;
...
}
...
float x = 1.234;
((func_t) &float_func)((param_t) x);
The float is first being converted to an integer type and then back. As a result the value might be rounded. An obvious solution would be to take an address of x and pass it to modified a function float_func2(float *value_ptr). The function would dereference its pointer argument and get the actual float value.
But, of course, being hardcore C-programmers we do not want to be obvious, so we are going to resort to some ugly trickery.
// Problem fixed the true C-programmer way.
void float_func(param_t param) {
float value = *((float *) ¶m);
...
}
...
float x = 1.234;
((func_t) &float_func)(*((param_t *) &x));
The difference of this sample compared to passing a pointer to float, is that on the architecture (like x86-64) where parameters are passed on registers rather than on the stack, a smart enough compiler can make float_func do its job using registers only, without the need to load the parameter from the memory.
One option is for all the functions accept a char * argument, and your calling code to always pass one. The functions that don't need an argument need not use the argument they receive.
To be clean (and avoid undefined behaviour), if you must have some functions that accept no argument and some functions that accept an argument, use two lists and register/call each type of function separately.
If the behaviour is undefined there's no telling how much damage could be caused.
It might blow up the planet. Or it might not.
So just don't do it, OK?
I am in a problem with a design question in C.
Let's say that I have a pretty large amount of functions, with different argument count.
POQ:
int print_one(int x)
{
printf("one: %d\n", x);
return 1;
}
int print_three(int x, int y, int z)
{
printf("three: %d-%d-%d\n", x, y, z);
return 3;
}
Now, I want to connect some properties to these functions in a structure, so that I can manipulate them without knowing the exact function, including their parameter count (I might even call the structure interface)
I tryd it like this, (& I think is pretty wrong):
typedef int (*pfunc)(int c, ...);
typedef struct _stroffunc
{
pfunc myfunction;
int flags;
int some_thing_count;
int arguments[10];
int argumentcount;
} stroffunc;
int main()
{
stroffunc firststruct;
firststruct.pfunc = (pfunc) print_two;
firststruct.something_count = 101;
arguments[0] = 102;
argumentcount = 1;
flag &= SOME_SEXY_FLAG;
// now I can call it, in a pretty ugly way ... however I want (with patially random results ofc)
firststruct.pfunc(firststruct.arguments[0]);
firststruct.pfunc(firststruct.arguments[0], 124, 11);
firststruct.pfunc(1, firststruct.arguments[0], 124, 1, 1);
}
I find this solution very ugly, & I think (hope) that there is a better solution for calling & and setting the function pointers.
I'm just hoping, that I was clear enough ...
NOTE: I didn't compile this code, but i compiled & run a very similar one so the concepts are working.
NOTE: pure C needed
Calling a non-variadic function through a variadic function pointer leads to undefined behaviour. For a start, recall that the arguments to variadic functions undergo the default argument promotions (chars are converted to ints, etc.), which will totally screw things up.
It's not clear how or why you intend to dynamically call a function with differing numbers of arguments. But one solution could be to use a union:
typedef struct {
int num_args;
union {
void (*f1)(int);
void (*f2)(int, int);
void (*f3)(int, int, int);
} func;
} magic;
...
magic m;
...
switch (m.num_args) {
case 1: m.func.f1(arg1); break;
case 2: m.func.f2(arg1, arg2); break;
case 3: m.func.f3(arg1, arg2, arg3); break;
default: assert(0);
}
A second solution would be to rewrite all of your functions as variadic.
This is on the edge of my knowledge, but I believe that you need to make the functions variadic as well, due to incompatibilities in the ABI.
see: wikipedia's example
Maybe you can add a library which have some functions to handle the struct, like a "pseudo" class,
int initFunc(int (*pfunc)(int c,...));
This function will save the pointer into the struct, like a context in POO, in the struct you will use it like a "map" of all the function an you will call each one using an id.
which returns an id, and you save it in an array,
then another func say
int call(int id,int p1,...);
where you say the function id and the parameters, sure you must now which function is each id
Title pretty much sums this up. How come it's possible that i can assign a locally created Point a (in the function ReadPoint()) into a variable that's in a different scope. Doesn't the locally created Point a gets 'popped' away along with stack of function readPoint() ? What exactly is going on ?
struct Point readPoint(void)
{
struct Point a;
printf("x = ");
scanf("%lf",&b.x);
printf("y = ");
scanf("%lf",&b.y);
return a;
}
int main(int argc, char **argv) {
Point test = readPoint();
printPoint(test);
return 0
}
structs are no different to primitive types in this regard. It's exactly the same principle as:
int foo(void)
{
int x = 5;
return x;
}
int main(void)
{
int y = foo();
printf("%d\n", y);
}
The details of how this is achieved are implementation-dependent. But usually, the return value (whether it's an int or a struct) is placed onto the stack by the called function, and then the caller then can then access that stack location.
The struct is "copied", byte by byte, into test in main...just like returning an int from a function and assigning it to a variable.
This, however, wouldn't happen if you were returning a pointer to the struct and the dereferencing it and assigning (or something similar).
When returning, you'll create a copy of the object (with all members of the struct), but the local variable/object is still destroyed.
This will work unless you try to return a reference or pointer (in these cases your compiler should warn you about this stupid idea). This will work fine, unless you're trying to create a copy of something working with pointers.
In C++ this would include references too.
This is because on return from readPoint() all structure values are copied to another locally defined structure test. Structure a does not survive.
What you're seeing is structure assignment. Almost all modern compilers can handle this.
The function proto type like int xxxx(int) or void xxx(int)
You could use a global variable (or, a little better, you could use a static variable declared at file scope), or you could change your functions to take an output parameter, but ultimately you should just use a return statement, since that's really what it's for.
The two standard ways to return values out of functions in C are to either do it explicitly with the return statement, or to use a pointer parameter and assign into the object at the pointer.
There are other ways, but I'm not going into them for fear of increasing the amount of evil code in the world. You should use one of those two.
Use pass by reference:
void foo(int* x, int* y) {
int temp;
temp = *x;
x* = *y;
y* = temp;
}
void main(void) {
int x = 2, y=4;
foo(&x, &y);
printf("Swapped Nums: %d , %d",x,y);
}
You could have a global variable that you assign the value to.
You could pass an object that stores the integer, and if you change it in the function, it'll change elsewhere too, since objects are not value type.
It also depends on the programming language that you're using.
EDIT: Sorry I didn't see the C tag, so ignore my last statement
Typically you provide a reference to an external variable to your function.
void foo(int *value)
{
*value = 123;
}
int main(void)
{
int my_return_value = 0;
foo(&my_return_value);
printf("Value returned from foo is %d", my_return_value);
return 0;
}
The simple answer is given a prototype like the first one you must use the return statement as the int return value dictates it.
In principle it is possible to do something horrible like cast a pointer to an int and pass it in as a parameter, cast it back and modify it. As others have alluded to you must be sure you understand all the implications of doing this, and judging by your question I'd say you don't.
int wel();
int main()
{
int x;
x = wel();
printf("%d\n",x);
return 0;
}
int wel()
{
register int tvr asm ("ax");
tvr = 77;
}
Compiled with GCC compiler in ubuntu machine. In borland compiler, different way to return.
If you need to return more than one value, why not use a pointer to a new allocated struct?
typedef struct { int a, char b } mystruct;
mystruct * foo()
{
mystruct * s = (mystruct *) malloc(sizeof(mystruct));
return s;
}
Not tested, but should be valid.