How to solve "control reaches end of non-void function" warning? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
so in this function of mine, it is spitting out this warning: "carboard.c:79:1: warning: control reaches end of non-void function [-Wreturn-type]". Program runs fine, but i just want it to compile cleanly.
here is the code of the function:
int loadMainMenu()
{
char choice[LINE + EXTRA_SPACES];
Boolean menu = TRUE;
printf("\nWelcome to Car Board\n");
printf("--------------------\n");
printf("1. Play Game\n");
printf("2. Show Student's Information\n");
printf("3. Quit\n");
printf("\n");
printf("Please Enter Your Choice:\n");
do
{
int input;
fgets(choice, LINE + EXTRA_SPACES, stdin);
if (choice[strlen(choice) - 1] != '\n')
{
printf("BUFFER OVERFLOW!\n\n");
readRestOfLine();
}
choice[strlen(choice) - 1] = 0;
input = atoi(choice);
switch(input)
{
case 1: playGame();
break;
case 2: showStudentInformation();
loadMainMenu();
break;
case 3:
printf("Bye bye! \n");
return EXIT_SUCCESS;
break;
default: printf("Invalid input\n");
loadMainMenu();
break;
}
}while(menu);
}

You need to have a return statement in your code. Since your function is returning an integer you must have something likek return x; where x is an integer or you can declare function void.

The compiler is not that smart to figure out the do ... while never terminates.
To fix this, first ensure the loop cannot end by making it guaranted infinite using a constant:
do {
} while ( true );
If that doesn't work, try
while ( true ) {
...
}
The compiler might require a specific pattern ( for ( ; ; ) might also be worth a try; it is also a matter of personal preference).
If that still does not work, just return 0; after the loop above. That might be optimised away, so no extra code at best. At worst, you have to live with some dangling code.
An alternative would be to temporarily disable the warning using a pragma. That should really only be the last ressort.

Related

Some logical error always executes if block? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include<stdio.h>
#include<string.h>
char Sys_Pass[]="3699";
char verify_Pass(char *P,char *Q)
{
char ch;
ch=strcmp(P,Q);
printf("String Cmp %s,%s is %c %d\n",P,Q,ch,ch);
if(ch==0)
return 1;
else
return 0;
}
void main()
{
char Pass[10],New[10];
char fp=0,sp=0;
printf("Enter Password : ");
scanf("%s",Pass);
if(fp=verify_Pass(Pass,Sys_Pass))
{
Change: printf("Enter a New Password : ");
scanf("%s",Pass);
printf("Re-Type New Password : ");
scanf("%s",New);
if(sp=verify_Pass(Pass,New))
{
strcpy(Sys_Pass,New);
printf("Password Successfully changed\n");
printf("New Password : %s\n",Sys_Pass);
}
else
printf("Passwords Mismatch\n");
}
else
{
if(strcmp(Pass,"111999")==0);
goto Change;
printf("Wrong Password !!!\n");
}
printf("Fp : %c %d\nSp : %c %d\n",fp,fp,sp,sp);
}
This code is always executing the if block and provides the password change even though wrong current password is typed I want to know if there is a logical error if any ?
I am working on a 8051 project which i want to establish a secret password change i.e if i forgot a password and i type password as 111999 it should direct me to the password change menu but here it is always directing to change password menu. This was actually embedded C code but I tried to rectify that using C code but produces same output in both the cases.
You have a stray semicolon:
// here ---------------v
if(strcmp(Pass,"111999")==0);
goto Change;
As an aside, this is not a good use of goto. The better thing to do is check for either the current password or 111999 in the if condition.
printf("Enter Password : ");
scanf("%s",Pass);
if ((strcmp(Pass,"111999")==0) || (strcmp(Pass,Sys_Pass)==0))
{
printf("Enter a New Password : ");
...
}
else
{
printf("Wrong Password !!!\n");
}
There are several things in this code that have margin for improvement, but I will start by asking if you have used a debugger to debug the issue. If you haven't, you can check gdb: video here
I think also you should consider changing your main so it returns an int, except if you have a very good reason not to do it. Then you could have return codes. Same applies for the input arguments to main. If it receives none, I would strongly encourage you to specify it by typingint main(void). See here for more info
Personally I always add braces around every if/else block, even when it is one line. It helps avoid mistakes.
I dont have anything against the goto statement if it is used properly, but I believe in this case it is not. The Clean Code book by Robert Martin contains some good explanations on how to use it. I think you can try to rewrite this and avoid goto usage.

Equal to operator "==" is behaving like assignment operator "=" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am facing a very strange problem.
- I have an if condition:
if((IN_SYNC == sync_flag) || (cycle_number == spi_slot_number))
Before the condition, the variable "spi_slot_number" is '7' and after the if condition it was turned to '0' (which is the value of "cycle_number") !!!
Does any one knows how can such thing happen ?!
Important notes:
1- My code is in C language.
2- I checked the stack before and after the condition to make sure no stack corruption happening.
3- My program is one thread program, so no interrupts or other threads can interrupt.
4- If I commented the if condition , every thing goes fine.
5- I don't know how to generate the assembly code ...
As said by others, you haven't shared enough code to actually identify where your problem is. One thought that occurred to me however is the IN_SYNC identifier. It's a standard coding convention to put macros in all caps, and if it is a macro, it's possible that it's doing the dirty deed. Check for definition of IN_SYNC.
One other thing -- your if test has two tests, separated by an || operator. Try breaking the two tests apart to see which one is causing your side effect. Something like this:
printf("%d \n", spi_slot_number);
if (IN_SYNC == sync_flag) {
/* do nothing */
}
printf("after IN_SYNC test %d \n", spi_slot_number);
if (cycle_number == spi_slot_number) {
/* do nothing */
}
printf("after cycle_number test %d \n", spi_slot_number);
What happens if you do comparision on temporal copy of spi_slot_number? Does it work as expected?
void GetData(slot_id_T spi_slot_number, uint8_t* data_received,
uint16_t data_length, uint8_t data_is_valid_flag)
{
uint8_t cycle_number;
slot_id_T copy = spi_slot_number; // <- ADDED
cycle_number = GetCycleNumber() + 1;
if(cycle_number > LAST_CYCLE)
{
cycle_number = 0;
}
printf("%d \n", spi_slot_number);
if((IN_SYNC == sync_flag) || (cycle_number == copy)) // <- CHANGE
{
printf("%d \n", spi_slot_number);
switch(data_is_valid_flag)
{
case DATA_IS_VALID:
SendData(spi_slot_number, p_buffer, data_length);
break;
case DATA_IS_NOT_VALID:
IndicateDataNotValid(spi_slot_number, p_buffer, data_length);
break;
default:
/* Do Nothing */
break;
}
}
}

I am getting runtime error (SIGSEGV) in a c program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why I am getting runtime error (SIGSEGV) on the following code:
#include<stdio.h>
#include<string.h>
int main()
{
int t_line,count[10000],i;
scanf("%d",&t_line);
for(i=1;i<=t_line;i++)
{
fflush(stdin);
gets(t);
count[i]=(int)t[0]+(int)t[1]+(int)t[2];
}
for(i=1;i<=t_line;i++)
printf("%d\n",count[i]);
return 0;
}
I have also tried to solve this problem by initialized all the elements of array.
I am wondering how the code compiled, without declaration of the variable t. But, still the only missing elemnt was: char t[your choice of size];. Apart from that
#include<stdio.h>
//#include<string.h> No need of this header,a s you are not using any string functions
int main()
{
int t_line,count[10000],i;
char t[64];//you need to declare the variable before using it
scanf("%d",&t_line);
//Its safer if you check this
if(t_line >= 10000)//if you use 0 and < t_line in for loop below then change the condition to: if(t_line > 10000)
{
printf("ERROR: Limit exceeded. Not enough memory.\n");
return 1;//or you could use exit(1); and #include <stdlib.h>
}
for(i=1;i<=t_line;i++)//suggested: for(i=0;i<t_line;i++)
{
//fflush(stdin);
//gets(t);
char *rc = fgets(t, sizeof(t), stdin);
if(rc != NULL)
{ t[strlen(t) - 1] = '\0';\\because fgets gets the \n into the string too. This line makes fgets similar to gets, improving safety from overflow.
}
else
{
// handle fgets failed error
}
count[i]=(int)t[0]+(int)t[1]+(int)t[2];
}
for(i=1;i<=t_line;i++)//suggested: for(i=0;i<t_line;i++)
printf("%d\n",count[i]);
return 0;
}
Find the solution and suggested changes inline as code comments.
In C, its better to use indexes starting from 0, unless there is a specific requirement to use other values.

Case/Break and '{' in my function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm working on my latest new function. Any explanations would be great since I'm new to programming. I couldn't figure out how to fix this because the errors I got are:
18 syntax error before '{' token
20 case label not within a switch statement
21 (same as above)
22 (same as above)
23 `default' label not within a switch statement
29 [Warning] `return' with a value, in function returning void
32 [Warning] assignment makes pointer from integer without a cast
34 [Warning] `return' with a value, in function returning void
void moveCar(char board[], char vehicle, char direction, int distance)
{
int i;
int position, newPosition;
int offset;
for (i = 0; i < size; i++) //the main loop for the vehicles and user's input
{
if(isalpha(vehicle))//vehicles for all letters but 'x'
{
if(board[i] == vehicle)//vehicles on board
{
swtich(direction)
{
case 'r': offset = 1; break;
case 'l': offset = -1; break;
case 'u': offset = -8; break;
case 'd': offset = 8; break;
default: printf("invalid direction"); break;
newPosition = position + offset;
if(newPosition != '.')
{
printf("invalid move.");
return 0;
}
board = '.';
board[newPosition] = vehicle;
return 1;
}
}
}
}
It looks like you have a typo of Switch as Swtich, the compiler won't recognize it, and the case statements will fail to compile.
Additionally you close your switch statement too early. If you want those commands to execute only in default move them before the break. If you want them to execute for every case move them outside of the switch statement entirely

program running through my if else after function call

I have a class assignment in C to make a simple calculator that performs three calculations. I haven't completed all of the functions yet but I am having a problem with my calcMenu function. When the function is called the program runs through all of the if else statements and unknown to me, performs only the else statement which is error checking. Than the function is run again which is intended but this time it does not run through all of the if else statements and allows the user to make a choice. I know I have done something really stupid but have been racking my brain for the last hour. If anyone has any pitty for me, than please point me in the right direction. I know all the system calls will Irk some but this is a basic class and our instructor has told us to use them.
Thanks in advance,
Mike
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")
//Prototype calculate functions here
void evenOrOdd(int userNumber);
void squareNum(int userNumber);
void cubeNum(int userNumber);
void calcMenu(int userNumber);
void main() {
//Declare local variables here
int userNumber = 0;
printf("\t\t\tThe amazing three function caluculator\n\n\n");
printf("Please enter a whole number that you would like to calculate\n");
scanf("%d", &userNumber);
calcMenu(userNumber);
}
void calcMenu(int userNumber)
{
char calculateOption;
printf("\nWhat calculation would you like to perform with your number?\n\n");
printf("Press A.) to check if your number is even or odd.\n\n");
printf("Press B.) to calculate the square of your number.\n\n");
printf("Press C.) to calculate the cube of your number.\n\n");
printf("press D.) to exit the program.\n");
scanf("%c", &calculateOption);
calculateOption = toupper (calculateOption);
if (calculateOption == 'A')
{
evenOrOdd(userNumber);
}
else if (calculateOption == 'B')
{
squareNum(userNumber);
}
else if (calculateOption == 'C')
{
cubeNum(userNumber);
}
else if (calculateOption == 'D')
{
system("cls");
printf("Thank You for using my amazing calculator.\n\n");
system ("pause");
system ("exit");
}
else
{
printf("Please enter a valid choice");
calcMenu(userNumber);
}
}
void evenOrOdd(int userNumber) {
userNumber = userNumber %2;
if (userNumber == 0)
{
printf("Your number is even. \n");
}
else
{
printf("Your number is odd. \n");
}
}
void squareNum(int userNumber) {
}
void cubeNum(int userNumber){
}
When you read input with scanf you have to press the Enter key to make the program continue. Your scanf call reads the single character from the input, but leaves the Enter key still in the input buffer, to be read next time you call scanf.
There is a very simple trick to solve that: Place a space in the scanf format string before or after the "%c". This will make scanf skip whitespace.
scanf("%c ", &calculateOption);
If you stepped through the code with a debugger you would have easily seen that calculateOption would have been the newline character.
First of all, You can condense all those printf statements into one function to save the extra calls.
Next, you should probably indent your functions, I can't tell where one begins and another ends at a glance.
Third, don't use system("pause"), use getchar().
Fourth, this is optional, you might want to turn those if statements into a switch statement.
Now, on to your question. First of all, instead of using scanf("%c", &calculateOption), just use getchar() here too. In this case, I would write calcMenu() as this:
int calcMenu(int userNumber){
printf("\nWhat calculation would you like to perform with your number?\n\n\
Press A.) to check if your number is even or odd.\n\n\
Press B.) to calculate the square of your number.\n\n\
Press C.) to calculate the cube of your number.\n\n\
Press D.) to exit the program.\n");
switch(toupper(getchar())){
case 'A':
evenOrOdd(userNumber);
break;
case 'B':
squareNum(userNumber);
break;
case 'C':
cubeNum(userNumber);
break;
case 'D':
system("cls"); //this is bad, really.
printf("Thank You for using my amazing calculator.\n\n");
getchar();
return 0;
default:
printf("Please enter a valid choice: ");
calcMenu(userNumber);
break;
}
}
Also, main should always return a value. void main is bad practice.
Disclaimer: The code isn't tested, you shouldn't copy/paste it anyways. I also don't know if you're being forced to use some things or not...

Resources