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

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

Related

I always get the same if [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 1 year ago.
Improve this question
int main(int argc, char *argv[]) {
int hacim,yas;
char ad[20]; //Kullanıcı adı
printf("Kullanici adinizi girin: \n");
scanf("%s", ad);
printf("Sifrenizi girin: \n");
char sifre[20]; // Şifre
scanf("%s", sifre);
if (strcmp(ad,"ahmet")==0 && strcmp(sifre,"1234")==0){
printf("Giris basarili. Hosgeldiniz\n\n");
}
else
{
printf("Hatali giris yaptiniz \n");
}
printf("Aracin motor hacmini giriniz:");
scanf("%d",&hacim);
printf("\nAracin model yilini giriniz:");
scanf("%d",&yas);
if(1<=yas<=3 && 0<=hacim<=1300){
printf("\nOdemeniz gereken tutar 646TL");
}
else if(1<=yas<=3 && 1301<=hacim<=1600){
printf("Odemeniz gereken tutar 1035TL");
}
else if(4<=yas<=6 && 0<=hacim<=1300){
printf("Odemeniz gereken tutar 450TL");
}
else if(4<=yas<=6 && 1300<=hacim<=1600){
printf("Odemeniz gereken tutar 776TL");
}
else{
printf("yanlis deger");
}
return 0;
}
I always get 646 even with different values. Why is this happening?
1<=yas<=3
In C this expression is always true. Why? It can be written as (1<=yas)<=3
1<=yas can be 0 or 1. Both of those values are smaller than 3.
You need to use logical expression to have more complex number comparisons:
if(yas >= 1 && yas <= 3)
You need to change all simialt expressions in your program.
0<=hacim<=1300
This expression performs the first relational operation because of the precedence of the operator,it's obviously going to be 1.And then you compare 1 to 1300, and obviously you still get 1.So as long as hacim is greater than 0, it's going to be 1. That's what went wrong.

How to find if all brackets are balanced (C) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I have an array full of brackets, for example :
1) (()())())((())(())
2) ()((()()))
Any open bracket ( '(' ) should also be closed by another one (')')
So for example 1) ->
(()())())((())(()) -> (....)..)((..)(..) -> ())(()() -> .)(.. , so the answer is no because from here we can see that not all of the brackets are balanced
For example 2) ->
()((()())) -> .((..)) -> (()) -> (..) -> () -> .. , so here the answer is yes because all brackets are balanced. In this case, I would also like to print the positions of all couples of brackets that are balanced, for example :
1,2 & 5,6 & 7,8 & 3,10 & 4,9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In your case, it's as simple using a counter. Increment for (, and decrement for ). It shouldn't go under 0, and should be 0 in the end if balanced.
You may consider using a stack, if you're creating some syntax parser like the compilers and interpreters do.
EDIT: you need to use a stack to print out the pairs. You need to implement a stack by hand in C, so the following is reference code in C++.
std::stack<int> s;
switch(string[i]) {
case '(':
s.push(i);
break;
case ')':
if(!s.empty()) {
printf("%d, %d\n", s.top(), i);
s.pop();
} else {
// Fail here
}
break;
}
if(!s.empty()) // Fail here
Count opening and closing brackets:
const char* it;
int open_n = 0, close_n = 0;
/* Assume array is zero terminated.
* Otherwise condition: 'it != &array[ArraySize]' instead '*it' */
for(it = &array[0]; *it ; ++it) {
switch( *it ) {
case '(': open_n += 1; break;
case ')': if( open_n ) { close_n += 1; break; }
else { return false; /* ErrorCloseWithoutOpen */ }
default: break;
}
}
return open_n ? false : true;

How to solve "control reaches end of non-void function" warning? [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
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.

break statement doesn't work in a loop [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 7 years ago.
Improve this question
I saw a tutorial that explaining how to use the "break" statement in a loop
but every time i'm trying to use it i'm getting a compilation error saying:
"break statement not within loop or switch
break;"
This is my code:
if (finalFirstChar > 6 || finalFirstChar < 1)
{
printf("You didn't entered a proper number! \n");
break;
}
FWIW, if is a condition (selection statement, to be exact), and break works in a loop (iteration statement)/switch-case statement.
As per C11, chapter §6.8.6.3
A break statement shall appear only in or as a switch body or loop body.
In any case, you don't need a break in a if statement body.
OK:
while (cond1) {
if (cond2) break; /* or continue; */
if (cond3) return [something];
}
for (init; cond4; after) {
if (cond5) break; /* or continue; */
if (cond6) return [something];
}
do {
if (cond7) break; /* or continue; */
if (cond8) return [something];
} while (cond9);
if (cond10) return [something];
NOT OK:
if (cond11) { /* not in any while/do/for loop, or case switch */
break; /* or continue; */
}

what has mistaken with the switch command in C? [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
Here i just experienced with the switch command and if command at C. I have omitted the if command by comment and wrote the same command by using switch command. But its now working as i gave the instruction. Where i have mistaken? As i am a learner please pardon my mistakes..
#include <stdio.h>
#include<stdlib.h>
int main()
{
char card_name[3];
puts("enter the card name: ");
scanf("%2s", card_name);
/*int val=0;
if (card_name[0]=='K') {
val=10;
} else if (card_name[0]=='Q'){
val=10;
} else if (card_name[0]=='J'){
val=10;
} else if (card_name[0]=='A'){
val=11;
}else{
val=atoi(card_name);
}*/
int val=0;
switch (card_name[0]) {
case 'K':
case 'Q':
case 'J':
val=10;
break;
case 'A':
val=11;
default:
val=atoi(card_name);
break;
}
if (val>2 && val<7) {
puts("the count has gone up!");
} else if(val>=10){
puts("The count has gone down");
}
return 0;
}
You're missing another break in the 'A' case. Your switch statement then should look something like this (I added indentation for you).
switch (card_name[0]) {
case 'K':
case 'Q':
case 'J':
val=10;
break;
case 'A':
val=11;
break; // you were missing a break statement here
default:
val=atoi(card_name);
break;
}
There is no break; for case 'A' .. Is that intentional ?
You are missing a break statement in case 'A':,before the default label. You should break after each statement in a case statement unless it was your intent to have the other cases execute, as well as a given case.

Resources