How to cancel second function only if first function executes in C? - c

The two functions are about 200 lines since its a bunch of case statements (and they do work properly) so instead of showing I'll just explain what it does. I am currently creating a game similar to checkers.
Function 1: Checks if user input a valid move. If they did not then it would print out "invalid move".
Function 2: Updates the piece that has been moved on the board and displays the new updated board.
In the main function I did a while loop so if user input an invalid move, they will be prompted again. It does that but the board would still be updated. For example: if they chose to move piece 1 to a spot that piece 3 is occupying, the board will update: piece 1's spot is now empty even though it printed out "invalid move". I do not know how to stop function 2 if function 1 printed something.
Here is what I put in the main function.
char pieceToMove, emptySpot;
int moveNumber = 0;
int piecesOnBoard = 15;
while (piecesOnBoard >= 1, ++moveNumber) {
//prompting user input
printf("%d. Enter your move:", moveNumber);
scanf(" %c %c", &pieceToMove, &emptySpot);
checkMoves(pieceToMove, emptySpot, all, the, pieces, ect);
updateBoard(all, the, pieces);
}

Have function 1 return the equivalent of a Boolean value (1 or 0 — true or false, respectively, in C) depending on whether function 1 was successful or if it failed. Check that value before deciding to run function 2 (or not).
One way to do this is define a boolean_t convenience type and kTrue and kFalse values in your header file. These are int values underneath the hood, but this makes code easier to read:
typedef enum boolean {
kFalse = 0,
kTrue
} boolean_t;
In your header file, declare that your first function function_one() will return a boolean_t:
boolean_t function_one(...); /* "..." are the arguments this function takes */
In your implementation file, you write function_one() so that it returns either kTrue or kFalse, depending on whether its work succeeds or fails:
boolean_t function_one(...) {
do_stuff();
if (some_step_fails) {
return kFalse;
}
return kTrue;
}
Again in the implementation file, write the call to function_two() so that it runs only if the return value of function_one() was kTrue:
if (function_one(...) == kTrue) {
function_two();
}
else {
fprintf(stderr, "Error: Something went wrong...\n");
}

Related

How to implement a fsm

I want to parse output from a commandline tool using the fsm programming model. What is the simplest implementation of a fsm that is possible for this task?
Basically, the core idea of a finite state machine is that the machine is in a "state" and, for every state, the behaviour of the machine is different from other states.
A simple way to do this is to have an integer variable (or an enum) which stores the status, and a switch() statement which implements, for every case, the required logic.
Suppose you have a file of the followin kind:
something
begin
something
something2
end
something
and you duty is to print the part between begin/end. You read the file line by line, and switch state basing on the content of the line:
// pseudo-C code
enum state {nothing, inblock};
enum state status;
string line;
status = nothing;
while (!eof(file)) {
readline(line);
switch(status) {
case nothing:
if (line == "begin") status=inblock;
break;
case inblock:
if (line == "end")
status=nothing;
else print(line);
break;
}
}
In this example, only the core idea is shown: a "status" of the machine and a mean to change status (the "line" read from file). In real life examples probably there are more variables to keep more informations for every state and, perhaps, the "status" of the machine can be stored in a function pointer, to avoid the burden and rigidity of the switch() statement but, even so, the programming paradigm is clean and powerful.
The fsm model works in C by assigning function pointers to certain functions that have to process certain data. One good use for fsms is for parsing commandline arguments, for parsing captured output.... The function pointer is assigned to a preset starting function. The start function assigns the function pointer, which must be passed along, to the appropriate next function. And that decides the next function and so on.
Here is a very simple implementation of a fsm:
struct _fsm
{
void (*ptr_to_fsm)(struct _fsm fsm);
char *data;
}
struct _fsm fsm;
fsm->ptr_to_fsm = start; // There is a function called start.
while (fsm->ptr_to_fsm != NULL)
{
fsm->ptr_to_fsm(&fsm);
}
void start (struct _fsm fsm)
{
if (fsm->data == NULL)
{
fsm->ptr_to_fsm = stop; // There is a function called stop.
}
/* Check more more conditions, and branch out on other functions based on the results. */
return;
}
void stop (struct _fsm fsm)
{
fsm->ptr_to_fsm = NULL; /* The while loop will terminate. */
/* And you're done (unless you have to do free`ing. */
}

C program forcing me to have return type but I don't need it.!

I have a TCP/IP application in C. I have 1 header file for handling TCP/IP related things & 1 main file to call all functions. Since problem is happening on client side, I am posting my client side code only.
Here is program.c
#include "tcpHeader.h"
#include <pthread.h>
#include <stdio.h>
int main(int argc, char **argv){
// all code regarding connecting to server on TCP on another thread.
// Join here after completing the thread execution
// It works completely fine upto the next line.
testFunctionFromMyHeader();
// after executing below line, program do not continue with 'void' return type of the function.
// But it works if I change return type to 'int'
waitForAMessageFromServerAndSendConfirmation(12345678901LL);
// program expects me to return an integer on last function call
// & all other calls from now.
// even if I don't need integer return type.
testFunctionFromMyHeader();
return 0;
}
Here is tcpHeader.h
#ifndef CLIENT_TCP
#define CLIENT_TCP
// all required headers.
// all global variables
void testFunctionFromMyHeader(){
printf("Test Function");
}
void waitForAMessageFromServerAndSendConfirmation(unsigned long long args){
// wait until receiving data from server in recv() function.
// received 'args' is used in processing the data.
// process the data received
// send the confirmation message to server in send() function.
// Server also received this confirmation without any problem on server side.
// all code in this function also worked properly.
// Even the next printf line is also executed.
printf("All operation completed.");
// with 'void' return type, next line does not make any difference.
// But if I return an 'int' then it works.
return NULL;
}
#endif
It stops on waitForAMessageFromServerAndSendConfirmation(unsigned long long) in program.c
but If I do like this in program.c, then it works.(Return type on functions from tcpHeader.h are also changed to appropriate types)
int confirmation = waitForAMessageFromServerAndSendConfirmation(12345678901LL);
if( confirmation == 0 ){ // 0 or any int value
int testFunctionReturnedValue = testFunctionFromMyHeader();
.
.
.
// keep going like this with int return type FOR ALL FUNCTIONS
}
Help me to identify the problem. I don't want to use int return types everywhere.
- Why do it force me to have 'int' return type on waitForAMessageFromServerAndSendConfirmation(unsigned long long) function in my header file
- Why do it force me to have 'int' return types on all functions called after that one.
When a function is declared as void it means the function will not return anything.
If you use a return statement with a value in such a function, e.g. return 1;, you attempt to have it return something. But it is defined as not to return something.
Declaring a funcion as void has two intentions:
Tell the user of the function not to expect a return value.
Tell the author of the function not to return anything. If the author wants to communicate something, he should do that using other means (e.g. have a pointer argument to a variable of the caller in which to place a result value, or adapt the function signature to return something other than void).
For example:
void myFunc1(int*result) {
*result= 1; // put value 1 in callers variable
// there is no return statement that returns a value
}
void myFunc2(int*result) {
*result= 1; // put value 1 in callers variable
return; // leave the function. There is no value to return.
}
or:
int myFunc(int in) {
return 2*in; // leave the function and return a value.
}
To get back to your problem:
int confirmation = waitForAMessageFromServerAndSendConfirmation(12345678901LL);
The above says to expect the function to return something and to assign that to variable conformation. However,
void waitForAMessageFromServerAndSendConfirmation(unsigned long long args) {
//....
return NULL;
says the function will not return anything, but you try to let it return something.
because of these contradictions, your compiler complains.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

Why does my function return 0 instead of the number of lines in a file?

I have written a function that is supposed to read the number of sentences in a .txt file, but when the function is called and done, it gives me a value of 0.
This program over all has 3 more functions to figure out different properties of the file and I have them working great. This one is laid out the same way I wrote my other functions just looking for some advice on why I am getting 0 as my number of sentences.
void ptrCntS (FILE* sp1, int sCount)
{
char sentence = 'O';
int myChr;
if (!(sp1 = fopen("Hello.txt", "r")))
{
printf("error opening Hello.txt");
return(1);
}
while ((myChr = fgetc(sp1)) != EOF)
{
if ('.')
{
sentence ='O';
}
else if (sentence == 'O')
{
sCount++;
sentence = 'I';
}
}
fclose(sp1);
printf ("Total number of sentences are:\t%d", sCount);
return;
}
instead of return use return(sCount);
and assign the return value to some int variable in calling function
like
int sentCount;
.
.
.
sentCount=ptrCntS (param1,param2);
if ('.') is always true, thus else... code never reached. Use if( myChr == '.' ) instead.
Function compiles now and runs properly. This function is being called from a switch in a previous function where I had my addresses set and included my print statement for the totals so that I would not have to write another function in the end to call on all my counts and print their results. Instead I set my case 'A': to call all of my counting functions(in this case that is what the original code is) and than display my results. I am sorry for any lengthiness or my hard to understand writing I am new to the C language and I am having a hard time grasping the literature but making some process on understanding the syntax.

optimizing/ better way of coding a function and using its return value

I have some 20 to 30 functions, i have to call wsse_authenticate, in ever function for, and this wsse_authenticate function returns a value based on that value i send the fault message, Is there any way i can improve this code, so that i just call the function wsse_authenticate(soap) in every function and the switch case be replaced by some better code, i want to make it much efficient, Pls give me some inputs
wsse_ret = (wsse_authenticate(soap));
if(wsse_ret)
{
switch(wsse_ret)
{
case 1: onvif_fault(soap,"ter:NoSecuritytoken","ter:Failed_wsse_Aunthentication");
case 2: onvif_fault(soap,"ter:InvalidUserName","ter:FailedAunthentication");
case 3: onvif_fault(soap,"ter:InvalidPassword","ter:FailedAunthentication");
}
}
From the above code, I see that you are calling same function for all the cases expect for the "failure message" passed as an argument to function onvif_fault. And also there is no break after each case statement which would not give you result as expected.
Explanation for using break statement:
Suppose ret value is 1, then all the three cases would be executed since there is break statement at the end. Which means onvif_fault will be called three times with different parameters which is not expected.
Solution for you question
You can create a table using structures in c which actually has the list of the faults.
This was you can replace your Switch statements with only one line of code.
EX:
typedef struct _fault_messages
{
char msg1[254];
char msg2[254];
} fault_messages;
fault_messages msg_table[3] = {
{"ter:NoSecuritytoken", "ter:Failed_wsse_Aunthentication"},
{"ter:error1", "ter:fault1"},
{"ter:error2", "ter:fault2"}
};
Now, your fault messages in the above table are mapped. You can optimize your code as mentioned below:
wsse_ret = (wsse_authenticate(soap));
if(wsse_ret)
{
onvif_fault(soap, msg_table[wsse_ret-1].msg1, msg_table[wsse_ret-1].msg2);
}
If I understood correctly - your main problem is that you don't want to repeat security checking code in each and every function from 30 function set :-)
If that is the case you can try to use such pattern:
#include <stdio.h>
#include <string.h>
int isUserPasswordValid(char * password) {
return strcmp(password, "MyBigPassword") == 0;
}
#define callFunctionWithAuthentication(password, secPayload, execPayload) \
do {\
if (!isUserPasswordValid(password)) {\
secPayload\
}\
else {\
execPayload\
}\
} while(0);
int myTestFunction(int x) {
return x;
}
int main(int argc,char* argv[]){
// bad password - executes only authentication
callFunctionWithAuthentication(
"randomPassword",
printf("oops - bad password - can't continue\n");,
int a = myTestFunction(10); printf("function returned %d\n",a);)
// good password - executes authentication AND code after
callFunctionWithAuthentication(
"MyBigPassword",
printf("oops - bad password - can't continue\n");,
int a = myTestFunction(10); printf("function returned %d\n",a);)
return 0;
}
Only drawback that you must replace the call of each 30 function into the call of callFunctionWithAuthentication. But this is one-time task. Further you must always call this macro instead of plain function.

Resources