c Many advanced functions are built in , Let's start with the sort function

 #include <stdio.h>
#include <stdlib.h>
#include <string.h> int compare_score(const void *n1 ,const void *n2) { int *a = (int *)n1;
int *b = (int *)n2;
return *a - *b;
} int compare_name(const void *n1 , const void *n2) { char **a = (char **)n1;
char **b = (char **)n2;
return strcmp(*a, *b);
} int main(int argc, const char * argv[]) { int array[] = {,,,,,,,}; qsort(array, , sizeof(int), compare_score); for (int i = ; i < ; i++) {
printf("%i \n",array[i]);
} char *name[] = {"abc","efs","ss","gds","aaa","fee"};
qsort(name, , sizeof(char *), compare_name);
for (int i = ; i < ; i++) {
printf("%s \n",name[i]);
} return ;
}

The output is

In order to make this qsort The sorting function adapts to many kinds of sorting situations , You need to pass in a collation function as a parameter .

The following describes the use of a function pointer array

If we want to write a mass email program , Send different types of content to different people , It's natural to think of , We use it struct To achieve

 #include <stdio.h>
#include <stdlib.h>
#include <string.h> /**
Create an enumeration containing the type you want to save the type data
*/
enum response_type {
DUMP, /// Abandon
SECOND_CHANCE, /// Give me a chance
MARRIAGE /// cooperation
}; /**
* Create a structure , Used to save the name and type of the corresponding
*/
typedef struct {
char *name;
enum response_type type;
}reponse; /**
* To the responder p send out dump mail , Just look at this function , There are no restrictions
*/
void dump(reponse p) {
printf("Dear: %s \n",p.name);
puts("Unfortunately your last date contacted us to");
puts("say that they will not be seeing you again");
} /**
* The way to give a chance
*/
void second_chance(reponse p) {
printf("Dear: %s \n",p.name);
puts("Good news: your last date had asked us to");
puts("arrange another meeting. Please call AA");
} /**
* The way to cooperate
*/
void marriage(reponse p) {
printf("Dear: %s \n",p.name);
puts("Congratulatons: your last date has contacted");
puts("us with a proposal of marriage");
} int main(int argc, const char * argv[]) { reponse p[] = {
{"James",DUMP},
{"Juces",SECOND_CHANCE},
{"Bande",SECOND_CHANCE},
{"Hanmeimei",SECOND_CHANCE}
}; for (int i = ; i < ; i++) { switch (p[i].type) {
case DUMP:
dump(p[i]);
break;
case SECOND_CHANCE:
second_chance(p[i]);
break;
default:
marriage(p[i]);
break;
}
} return ;
}

We use the structure to store the required data, and the result of printing is as follows

But the code is full of function calls , Every time it needs to be based on type To determine which function to call , If you need to add a new type in the future , It's going to change the code in a lot of places , This is not what we want to see

In fact, the next thought is similar to the above enumeration , We can put a class of things in an array , If you need to take a value in it, you can

void (*reponse_array[])(reponse) = {dump,second_chance,marriage};

After the transformation of function pointer array , So we have the following code

 int main(int argc, const char * argv[]) {
reponse p[] = {
{"James",DUMP},
{"Juces",SECOND_CHANCE},
{"Bande",SECOND_CHANCE},
{"Hanmeimei",SECOND_CHANCE}
}; void (*reponse_array[])(reponse) = {dump,second_chance,marriage}; for (int i = ; i < ; i++) { reponse_array[p[i].type](p[i]);
} return ;
}

The words above are wrong reponse Should be changed into response , There will be no changes here

Next Introduce the use of a function that can pass multiple parameters , similar printf function

There are many different kinds of wine to join a bar , Now you need to write a program , When we enter the name of the wine, we can get the price of the wine , It's simple , The procedure is like this

 #include <stdio.h>
enum drink {
MUDSLIDE,FUZZY_NAVEL,MONKEY_GLAND,ZOMBIE
}; double price(enum drink d) {
switch (d) {
case MUDSLIDE:
return 122.0;
break;
case FUZZY_NAVEL:
return 222.0;
break;
case MONKEY_GLAND:
return 322.0;
break;
default:
return 422.0;
break;
}
} int main(int argc, const char * argv[]) { printf("%f",price(MONKEY_GLAND)); return ;
}

Now we can get the price of wine , But now if I make such a request , We need to know the total price of several single wines . So we need to write a function like this

double total(,MUDSLIDE,FUZZY_NAVEL,MONKEY_GLAND);

Because the number of wine products input is not fixed , Therefore, the concept of variable parameter is naturally extended

Let's take a look at printing multiple int Function of

 void print_ints(int arg,...) {
va_list ap;
va_start(ap, arg);
for (int i = ; i < arg; i++) {
printf("%i \n",va_arg(ap, int));
}
va_end(ap);
}

After our modification, the code looks like this

 #include <stdio.h>
#include <stdarg.h> enum drink {
MUDSLIDE,FUZZY_NAVEL,MONKEY_GLAND,ZOMBIE
}; double price(enum drink d) {
switch (d) {
case MUDSLIDE:
return 122.0;
break;
case FUZZY_NAVEL:
return 222.0;
break;
case MONKEY_GLAND:
return 322.0;
break;
default:
return 422.0;
break;
}
} double total(int args,...) {
double total = 0.0;
va_list ap;
va_start(ap, args);
for (int i = ; i < args; i++) {
double p = price(va_arg(ap, enum drink));
total += p;
}
va_end(ap);
return total;
} int main(int argc, const char * argv[]) { printf("%f",total(,MUDSLIDE,MONKEY_GLAND,FUZZY_NAVEL)); return ;
}

The printout is

.000000Program ended with exit code: 

c More articles on the simple use of advanced functions

  1. SQL Server in row_number Simple use of a function

    One .SQL Server Row_number Function introduction   ROW_NUMBER() It's a Window function , It assigns a continuous integer to each row in the partition of the result set . The line number begins with the line number of the first line in each partition . Here are R ...

  2. python3 String formatting format() Simple use of a function

    format() function """ test format() function """ def testFormat(): # format() There are several elements in the function , ...

  3. 【 I have to learn python】open Simple use of a function

    open function 1, Usage method :open(' File path ', ' Pattern ', Encoding mode ). 2, Best use with open as: Save every time you need close() Link 3, Model is introduced : ①w Can write ( If there is , Will be covered ...

  4. JS Simple use of callback function in

    a Can take b,b Can get it c,c Can get it d, Realization a Get d Things that are . function a() { b(function (data) { console.log(data); }); } function b(c ...

  5. matlab in disp Simple use of a function

    Output data of array type , Also can put the string Data of type is treated as array output Output number >> num = ; >> disp(num) Output string >> disp('this i ...

  6. Oracle Of substr Function simple usage and substring difference

    substr( character string , Intercept start position , Interception length ) // Returns the truncated word substr('Hello World',0,1) // The return result is 'H'  * Starting from the first character of the string, the length is 1 String subst ...

  7. python Simple function definition and usage examples

    python Simple function definition and usage examples This article mainly introduces python Simple function definition and usage , Examples are analyzed Python Custom functions and how to use them , It has certain reference value , Friends in need can refer to The specific analysis is as follows : here ...

  8. Oracle Of substr Function simple usage

    substr( character string , Intercept start position , Interception length ) // Returns the truncated word substr('Hello World',0,1) // The return result is 'H'  * Starting from the first character of the string, the length is 1 String subst ...

  9. Oracle Of substr Function simple usage ( turn )

    turn :http://www.cnblogs.com/nicholas_f/articles/1526063.html substr( character string , Intercept start position , Interception length ) // Returns the truncated word substr('H ...

Random recommendation

  1. see macbook How many

    Prince-2:~ snowinmay$ uname -aDarwin Prince-2.local 12.5.0 Darwin Kernel Version 12.5.0: Sun Sep 29 ...

  2. dbca We couldn't find ASM disk

    The phenomenon dbca When creating a database , Can't find ASM Disk group : and grid The user to use asmca But you can see ASM Disk group . resolvent 1. Check the device permissions , The correct permissions are grid:asmadmin 2. Check GRID_HOM ...

  3. HDU 4006 The kth great number【 Priority queue 】

    The question : Input n That's ok ,k, If a line with I start , So insert x, If the Q start , Then output the second k Large number Do it with priority queues , Maintain the size of the queue at k So big , And then every time you take the first element of the team In addition, this maintenance queue only has k You need to pay attention to this when you create an element ...

  4. Socket Use

    import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import jav ...

  5. C Language foundation -- Structure alignment , Bit field , Consortium

    Structure alignment 1-- The reason and significance of structure alignment Many computer systems have some restrictions on the allowable addresses of basic data types , Requires that the address of a certain type of object must be a certain value K( Usually 2,4,8) Multiple , And this k Is called the alignment modulus of the data type ...

  6. OpenJudge 2813 The problem of painters / Poj 1681 Painter&#39;s Problem

    1. Link address : http://bailian.openjudge.cn/practice/2813 http://poj.org/problem?id=1681 2. subject : Total time limit : 1000ms ...

  7. Java Read Excel Another way

    In addition to using poi Read Excel Out of form , Also available ExcelHelper Read Excel. Code example String[] fieldNames = new String[] { "studentId&qu ...

  8. [android] Call the system camera and camera

    View the system camera source code , Find the manifest file to see Look at the intention filter ,action yes android.media.action.IMAGE_CAPTURE category yes android.intent.categor ...

  9. stay ASP.NET Core2.0 Baidu online editor is used in UEditor( turn )

    One . cause UEditor It's Baidu's rich text editor , For back-end upload processing, only Asp.Net Version of the support . If you want to .Net Core Project use , Then the background upload interface needs to be reconstructed . UEditorNetCore: hundred ...

  10. Two DIV Show... Side by side

    A project I did today , Need to do 3 individual div, One is the general frame (Div1), The other two are subframes , Fill in proportionally div1, I set up two div Of width and height, It turns out that the effect is two div Up and down display , As shown in the figure : If you want two DI ...