5 /** Pointer to a function with this profile */
6 typedef int(*operation_cb
)(int v1
, int v2
);
8 /** Describe a single operation */
14 int doAddition(int v1
, int v2
);
15 int doSubstraction(int v1
, int v2
);
16 int doMultiplication(int v1
, int v2
);
17 int doXOR(int v1
, int v2
);
19 /** All available operations */
20 operation_t operations
[4] = {
38 #define operations_count ((int) (sizeof(operations) / sizeof(operations[0])))
40 /** Display a prompt to the user then wait for an integer input. */
41 void promptValue(const char* prompt
, int* value
) {
42 printf("%s:\n", prompt
);
46 void displayMenuEntry(int index
, const char* label
) {
47 printf("%d | %s\n", index
, label
);
50 /** Display all available operations and an EXIT option. */
52 for (int menuIndex
= 0; menuIndex
< operations_count
; ++menuIndex
) {
53 displayMenuEntry(menuIndex
+ 1, operations
[menuIndex
].label
);
56 displayMenuEntry(operations_count
+ 1, "Exit");
59 /** Prompt the user for his operation choice.
61 * @return The selected operation. If the exit option is chosen, return NULL
63 operation_t
* promptOperation() {
68 promptValue("Choose an option", &result
);
70 if (result
== (operations_count
+ 1)) {
74 if (result
>= 1 && result
<= operations_count
) {
75 return &operations
[result
- 1];
78 printf("Please choose a valid option (1-%d)\n", operations_count
);
82 int doAddition(int v1
, int v2
) {
86 int doSubstraction(int v1
, int v2
) {
90 int doMultiplication(int v1
, int v2
) {
94 int doXOR(int v1
, int v2
) {
99 operation_t
* operation
= promptOperation();
101 if (operation
== NULL
) {
106 promptValue("Initial value", &initialValue
);
110 promptValue("Next value", &nextValue
);
112 if (nextValue
== 0) {
116 initialValue
= operation
->cb(initialValue
, nextValue
);
117 printf("Result: %d\n", initialValue
);