How do I create a C function? Something so that I can define a certain word, say help, as a function that is equivalent to:
printf("[Help stuff here]");
How do I create a C function? Something so that I can define a certain word, say help, as a function that is equivalent to:
printf("[Help stuff here]");
Oh my...
I don't understand what you want, can you try explaining it a different way?
You see, my problem is that I have a long bunch of code that appears repeatedly in my program. I don't want to type it over and over, and copying and pasting is too much work. So how can I make it so that I type one word instead of a whole bunch. E.g. the follwing 2 pieces of code are equivalent:
1. calculate
2. int x;
printf("blahblahblah");
int y;
printf("blahblahblah");
scanf("%d",x);
printf("blahblahblah");
scanf("%d",y);
int z;
z=x+y;
printf("blahblahblah);
So how can I do that?
You can create a function before the main function, eg
or you can define it at the end of main (conventional way) in which case you need to have a PROTOTYPE before main eg,Code:int calculate() { int a, b; /* prompt a*/ scanf("%d", &a); /* prompt b */ scanf("%d", &b); return a+b; } main() { int sum; ... sum = calculate(); ... return 0; }
Hope this helps.Code:int calculate(); /* <-- prototype */ main() { int sum; ... sum = calculate(); ... return 0; } int calculate() { int a, b; /* prompt a*/ scanf("%d", &a); /* prompt b */ scanf("%d", &b); return a+b; }
For the record, you can prototype functions inside of other functions:
Quzah.Code:int main( void ) { int myfunc( char * ); int x; x = myfunc( "Hello" ); return !!x; /* Just for fun. */ } int myfunc( char * s ) { printf( "%s\n", s ); return 5; }
Hope is the first step on the road to disappointment.
Building upon what Quzah just said:
Code:#include <ctype.h> int main( void ) { int myfunc( char *s) { for(;*s;s++) *s = toupper(*s); } char s[] = "hello"; myfunc(s); puts(s); return ~-1; /* Just for fun. */ }
yeah, nested function definitions are not a part of the standard