Home »
C programs »
C common errors programs
Here, we will learn why an error: case label not within a switch statement occurs and how to fix it in C programming language?
Submitted by IncludeHelp, on September 04, 2018
The error: case label not within a switch statement occurs in C language with switch case statement, when switch (variable/value) statement is terminated by the semicolon (;).
Example:
#include <stdio.h> int main(void) { int choice = 2; switch(choice); { case 1: printf("Case 1n"); break; case 2: printf("Case 2n"); break; case 3: printf("Case 3n"); break; case 4: printf("Case 4n"); break; default: printf("Case defaultn"); } return 0; }
Output
prog.c: In function ‘main’: prog.c:9:6: error: case label not within a switch statement case 1: ^~~~ prog.c:11:10: error: break statement not within loop or switch break; ^~~~~ prog.c:12:6: error: case label not within a switch statement case 2: ^~~~ prog.c:14:10: error: break statement not within loop or switch break; ^~~~~ prog.c:15:6: error: case label not within a switch statement case 3: ^~~~ prog.c:17:10: error: break statement not within loop or switch break; ^~~~~ prog.c:18:6: error: case label not within a switch statement case 4: ^~~~ prog.c:20:10: error: break statement not within loop or switch break; ^~~~~ prog.c:21:6: error: ‘default’ label not within a switch statement default: ^~~~~~~
How to fix?
See the statement switch(choice); it is terminated by semicolon (;) – it must not be terminated. To fix this error, remove semicolon after this statement.
Correct code:
#include <stdio.h> int main(void) { int choice = 2; switch(choice) { case 1: printf("Case 1n"); break; case 2: printf("Case 2n"); break; case 3: printf("Case 3n"); break; case 4: printf("Case 4n"); break; default: printf("Case defaultn"); } return 0; }
Output
Case 2
C Common Errors Programs »
LOLYOU1996 3 / 3 / 3 Регистрация: 25.08.2013 Сообщений: 39 |
||||||||
1 |
||||||||
26.08.2013, 21:55. Показов 17923. Ответов 6 Метки нет (Все метки)
Здравствуйте, работая с оператором switch произошла ошибка
Вот код
__________________
0 |
Don’t worry, be happy 17781 / 10545 / 2036 Регистрация: 27.09.2012 Сообщений: 26,516 Записей в блоге: 1 |
|
26.08.2013, 21:57 |
2 |
switch.
case label ‘1’ not within a switch statement
1 |
3 / 3 / 3 Регистрация: 25.08.2013 Сообщений: 39 |
|
26.08.2013, 22:04 [ТС] |
3 |
switch. о боже, и как я такое не заметил, аж стыдно, но все равно спасибо
0 |
3985 / 3255 / 909 Регистрация: 25.03.2012 Сообщений: 12,102 Записей в блоге: 1 |
|
27.08.2013, 01:38 |
4 |
следующий вопрос: «почему крестиками заполняется больше одной клетки?»
0 |
SatanaXIII Почетный модератор 5850 / 2861 / 392 Регистрация: 01.11.2011 Сообщений: 6,905 |
||||
27.08.2013, 11:13 |
5 |
|||
Решение
0 |
IDis 1 / 1 / 0 Регистрация: 20.05.2016 Сообщений: 47 |
||||
11.08.2016, 15:38 |
6 |
|||
Народ не могу понять что не так. и что значит case label ‘1’ not within a switch statement на русском что это означает?
0 |
John Prick 2060 / 1592 / 679 Регистрация: 27.07.2012 Сообщений: 4,768 |
||||
11.08.2016, 15:55 |
7 |
|||
на русском что это означает? Метка Добавлено через 48 секунд
1 |
- Forum
- Beginners
- error: case label not within a switch st
error: case label not within a switch statement
Hello everyone,
I just have an error in my switch. I checked online for an answer, but I didn’t find one :(.
Here is the code:
|
|
And my error is
error: case label not within a switch statement
The error is located here at the 28th line.
Help!
Cases need to be enclosed in a set of braces, like so:
|
|
Wazzak
Try wrapping that switch statement with curly brackets. switch (choixOperation) { …… }
Greetings,
It should be
|
|
How stupid I am!
How could I forget them!
Thank you anyway
Topic archived. No new replies allowed.
When I compile an application in Linux 5, Iget the following error.
api_svc1.c:335: error: case label not within a switch statement
api_svc1.c:340: error: âdefaultâ label not within a switch statement
c program ‘api_svc1.c’ is generated by rpcgen. Switch statement is not found in the geberated code.
The code fragment is given below:
result = (*local)((char *)&argument, rqstp);
if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) {
svcerr_systemerr (transp);
_exit (-1);
}
_exit (0);
case -1:
/*
* Error - fork couldn't create the child process, return
*/
svcerr_systemerr(transp);
default:
/*
* Parent process, clean up any zombie children and
* return to svc_run()
*/
svc_destroy(transp);
while (waitpid(-1,NULL,WNOHANG) > 0);
_rpcsvccount--;
_rpcsvcstate = _SERVED;
return;
The same code was generated and compiled successfully in Solaris without errors.
Any idea how to solve this?
11 Years Ago
The errors in the program say all the cases besdies the 1st ones inside the «woods»
function are not within a switch statement, i think its something to do with the if statments i have inside the switches, any help to help me solve this would be great, thanks everyone. Everything works besides the woods function.
inside the woods function it should work like this,
it checks your levels and if its 1 you fight the young rat, 2 you fight the large rat, 3 the troll and 4 the demon, this is done with the switch statment. then inside the cases it used an if statment to check if you damanged it down to 0 or below in which case it lets you exit the if statement to the experience part that levels you up if your experience is past a certain limit. just thought i should explain to make it easier
//Wayne Daly
//Header files
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<iomanip>
#include<string>
using namespace std;
//global variables
string name;
int level;
int health;
int maxhealth;
int gold;
int attack;
int experience;
void tavern();
void blacksmith();
void village();
void woods();
void potionshop();
void village();
void stats();
void stats()
{
cout<<"Name: " << name << " ";
cout<<"nLevel: " << level << " ";
cout<<"nGold: " << gold << " ";
cout<<"nAttack: " << attack << " ";
cout<<"nExperience: " << experience << " ";
cout<<"nHealth: " << health << "/" << maxhealth << " ";
getch();
village();
}
void blacksmith()
{
cout<<"Welcome to blacksmith, go 2 village";
getch();
village();
}
void potionshop()
{
cout<<"Welcome to potionshop";
getch();
village();
}
void woods()
{
cout<<"Welcome to woods";
getch();
if ( level == 1 )
{
int youngrat_choice;
int youngrat_health;
int youngrat_maxhealth;
youngrat_maxhealth = 10;
youngrat_health = youngrat_maxhealth;
cout<<"nYou enter in battle with a young ratn";
startfightyoungrat:
cout<<"It attacks you and deals you with 4 damagen";
health = (health - 4);
getch();
menuyoungrat:
cout<<"n1.Attack n2.Enemy's Stats n3.My Stats n4. Excape";
cin>>youngrat_choice;
switch (youngrat_choice)
case 1:
cout<<"nYou strike the young rat with your swordn";
youngrat_health = ( youngrat_health - attack );
cout<<"You deal the enemy " << attack << " damagen";
if ( youngrat_health <= 0 )
{
cout<<"You defeated the young rat and earned 5 experiencen points and 12 gold coinsn";
experience = (experience + 5);
gold = (gold + 12);
getch();
}
else if ( youngrat_health > 0 )
{
cout<<"The young rath is still alive!!";
getch();
goto startfightyoungrat;
}
case 2:
cout<<"nEnemys Stats: nnType: Young RatnHealth: " << youngrat_health << "/" << youngrat_maxhealth << " ";
getch();
goto menuyoungrat;
case 3:
cout<<"Name: " << name << " ";
cout<<"nLevel: " << level << " ";
cout<<"nGold: " << gold << " ";
cout<<"nAttack: " << attack << " ";
cout<<"nExperience: " << experience << " ";
cout<<"nHealth: " << health << "/" << maxhealth << " ";
getch();
goto menuyoungrat;
case 4:
cout<<"nYou run away in panic after being attackedn";
getch();
village();
getch();
}
else if ( level == 2 )
{
int largerat_choice;
int largerat_health;
int largerat_maxhealth;
largerat_maxhealth = 25;
largerat_health = largerat_maxhealth;
cout<<"nYou enter in battle with a large ratn";
startfightlargerat:
cout<<"It attacks you and deals you with 10 damagen";
health = (health - 10);
getch();
menulargerat:
cout<<"n1.Attack n2.Enemy's Stats n3.My Stats n4. Excape";
cin>>largerat_choice;
switch (largerat_choice)
case 1:
cout<<"nYou strike the large rat with your swordn";
largerat_health = ( largerat_health - attack );
cout<<"You deal the enemy " << attack << " damagen";
if ( largerat_health <= 0 )
{
cout<<"You defeated the large rat and earned 5 experiencen points and 12 gold coinsn";
experience = (experience + 5);
gold = (gold + 12);
getch();
}
else if ( largerat_health > 0 )
{
cout<<"The large rat is still alive!!";
getch();
goto startfightlargerat;
case 2:
cout<<"nEnemys Stats: nnType: large RatnHealth: " << largerat_health << "/" << largerat_maxhealth << " ";
getch();
goto menulargerat;
case 3:
cout<<"Name: " << name << " ";
cout<<"nLevel: " << level << " ";
cout<<"nGold: " << gold << " ";
cout<<"nAttack: " << attack << " ";
cout<<"nExperience: " << experience << " ";
cout<<"nHealth: " << health << "/" << maxhealth << " ";
getch();
goto menulargerat;
case 4:
cout<<"nYou run away in panic after being attackedn";
getch();
village();
getch();
}
else if ( level == 3 )
{
int troll_choice;
int troll_health;
int troll_maxhealth;
troll_maxhealth = 50;
troll_health = troll_maxhealth;
cout<<"nYou enter in battle with a trolln";
startfighttroll:
cout<<"It attacks you and deals you with 35 damagen";
health = (health - 35);
getch();
menutroll:
cout<<"n1.Attack n2.Enemy's Stats n3.My Stats n4. Excape";
cin>>troll_choice;
switch (troll_choice)
case 1:
cout<<"nYou strike the troll with your swordn";
troll_health = ( troll_health - attack );
cout<<"You deal the enemy " << attack << " damagen";
if ( troll_health <= 0 )
{
cout<<"You defeated the troll and earned 25 experiencen points and 58 gold coinsn";
experience = (experience + 25);
gold = (gold + 58);
getch();
}
else if ( troll_health > 0 )
{
cout<<"The troll is still alive!!";
getch();
goto startfighttroll;
case 2:
cout<<"nEnemys Stats: nnType: trollnHealth: " << troll_health << "/" << troll_maxhealth << " ";
getch();
goto menutroll;
case 3:
cout<<"Name: " << name << " ";
cout<<"nLevel: " << level << " ";
cout<<"nGold: " << gold << " ";
cout<<"nAttack: " << attack << " ";
cout<<"nExperience: " << experience << " ";
cout<<"nHealth: " << health << "/" << maxhealth << " ";
getch();
goto menutroll;
case 4:
cout<<"nYou run away in panic after being attackedn";
getch();
village();
getch();
}
else if ( level == 4 )
{
int demon_choice;
int demon_health;
int demon_maxhealth;
demon_maxhealth = 50;
demon_health = demon_maxhealth;
cout<<"nYou enter in battle with a demonn";
startfightdemon:
cout<<"It attacks you and deals you with 70 damagen";
health = (health - 70);
getch();
menudemon:
cout<<"n1.Attack n2.Enemy's Stats n3.My Stats n4. Excape";
cin>>demon_choice;
switch (demon_choice)
case 1:
cout<<"nYou strike the demon with your swordn";
demon_health = ( demon_health - attack );
cout<<"You deal the enemy " << attack << " damagen";
if ( demon_health <= 0 )
{
cout<<"You defeated the demon and earned 52 experiencen points and 108 gold coinsn";
experience = (experience + 52);
gold = (gold + 108);
getch();
}
else if ( demon_health > 0 )
{
cout<<"The demon is still alive!!";
getch();
goto startfightdemon;
case 2:
cout<<"nEnemys Stats: nnType: DemonnHealth: " << demon_health << "/" << demon_maxhealth << " ";
getch();
goto menudemon;
case 3:
cout<<"Name: " << name << " ";
cout<<"nLevel: " << level << " ";
cout<<"nGold: " << gold << " ";
cout<<"nAttack: " << attack << " ";
cout<<"nExperience: " << experience << " ";
cout<<"nHealth: " << health << "/" << maxhealth << " ";
getch();
goto menudemon;
case 4:
cout<<"nYou run away in panic after being attackedn";
getch();
village();
getch();
}
else {
cout<<"nErrorn";
getch();
village();
}
//start of level up after battle phase
if ( experience >= 9 )
{
level = 1;
}
else if ( experience > 9 && experience < 25 )
{
level = 2;
}
else if ( experience >24 && experience <=49 )
{
level = 3;
}
else if ( experience >= 50 )
{
level = 4;
}
getch();
village();
}
void tavern()
{
int choice_tavern;
cout<<"nWelcome to the local Tavern";
cout<<"n1. Room for the nightn2. Any news?n3. Exitnn";
cin>>choice_tavern;
switch (choice_tavern)
{
case 1: cout << "You wake up the following day feelingn";
cout << "fully refreshed * Health is now full *";
health = maxhealth;
getch();
break;
case 2: cout << "Hmm the evil forces from the woods seem to be more aggressiven";
getch();
break;
case 3: cout << "Goodbye!n";
getch();
break;
default: cout<< "Sorry I dont understand you!";
getch();
break;
}
village();
}
void village()
{
int village_choice;
//start village
cout<<"nnYou enter the village";
cout<<"n1. Tavernn2. Blacksmithn3. Potion Shopn4. Woodsn5. Stats nn";
cin>>village_choice;
switch(village_choice)
{
case 1: tavern();
case 2: blacksmith();
case 3: potionshop();
case 4: woods();
case 5: stats();
default: cout<< "Sorry I dont understand you!";
getch();
village();
}
}
int main()
{
health = 100;
level = 1;
maxhealth = 100;
gold = 0;
attack = 2;
experience = 1;
cout<<"Enter your name warrior!n";
cin>>name;
village();
}
Edited
11 Years Ago
by zendet because:
n/a
Пытаюсь написать калькулятор на Си, выдает ошибку
Код:
#include <stdio.h>
int main()
{
int a, b, result;
char c;
printf («Vvedite virajenie: «);
scanf («%d%c%d», &a, &c, &b);
switch (c);
{
case ‘+’:result=a+b;
printf («%d+%d=%d», a, b, result);
break;
case ‘-‘:result=a—b;
printf («%d-%d=%d», a, b, result);
break;
case ‘*’:result=a*b;
printf («%d*%d=%d», a, b, result);
break;
case ‘/’:result=a/b;
printf («%d/%d=%d», a, b, result);
break;
}
return 0;
}
выдает ошибки : case label `’+» not within a switch statement и т.д.
и еще break statement not within loop or switch
Что не так делаю?
2 ответа
360
02 декабря 2012 года
P*t*
474 / / 15.02.2007
Нет, надо просто точку с запятой после switch (c) убрать
1
02 декабря 2012 года
kot_
7.3K / / 20.01.2000
вероятно надо так
Код:
switch (c);
{
case ‘+’:
{
result=a+b;
printf («%d+%d=%d», a, b, result);
break;
}
…
}
|
|
|
Константа из класса, для case. Помогите с синтаксисом.
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Здравствуйте! Столкнулся тут с проблемкой. class SomeClass { public: SomeClass() { type = const0; } enum { const0, const1, const2 } type; }; И в одном месте, мне нужно получить доступ к этим константам из вне. Вот например так: SomeClass* sc = new Someclass(); … if( SomeClass::const1 == sc->type ) … Это работает. Но вот в многовариантном выборе возникают проблемы. switch( sc->type ) { // в следующей строке синтаксис не проходит case SomeClass::const0: … break; case SomeClass::const1: … break; case SomeClass::const2: … break; } Компилятор тут же начинает ругаться Цитата error: case label ` const0′ not within a switch statement И примерно так же на остальное. Пробовал брать выражение SomeClass::const0 в круглые скобочки — не помогло. Использую MinGW. Как написать по другому, не знаю. |
ss |
|
Senior Member Рейтинг (т): 41 |
В VC норм. Единственно, что смутило — SomeClass* sc = new Someclass(); Сообщение отредактировано: ss — 30.10.09, 09:23 |
Eric-S |
|
Ну такая запись у меня работала всегда нормально. А вот на строку Попробую ещё поэксперементировать. Добавлено 30.10.09, 10:37 |
AnarchyMob |
|
Может при объявлении перечисления нужно задать начальный индекс: enum { const0 = 0, const1, const2 } type; хотя компилятор их «автоиатом» с нуля индексирует. Сообщение отредактировано: AnarchyMob — 30.10.09, 11:54 |
Eric-S |
|
Значение инициализации, нельзя задавать в описании класса. Ошибку нашол. В очередной раз тупанул. Не весть откуда взялась фигурная скобочка, которая мне весь код испаганила. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0229 ] [ 16 queries used ] [ Generated: 9.02.23, 12:20 GMT ]