Error c2360 is skipped by case label



error C2360: initialization of ‘i’ is skipped by ‘case’ label ?

My program has an error C2360: initialization of ‘i’ is skipped by ‘case’ label.
I don’t know why. Please help me out!
thks!!

the error occurs in Division case 3.

  1. //Claire’s Calculator
  2. #include
  3. #include
  4. double pow(double x, double y);
  5. main()
  6. <
  7. int choice, choicee;
  8. const double PI = 3.14159;
  9. float a, b, c;
  10. int n, m;
  11. double cy;
  12. double x, y;
  13. float x_to_the_y;
  14. double r;
  15. int re, q;
  16. do //
  17. <
  18. cout > choice; //get choice from the user
  19. if ((choice 8))
  20. <
  21. cout 8));
  22. switch(choice)
  23. <
  24. case 1: // Addition
  25. cout > a;
  26. cout > b;
  27. cout > a;
  28. cout > b;
  29. cout > a;
  30. cout > b;
  31. cout > choicee;
  32. >
  33. while ((choicee 3));
  34. switch(choicee)
  35. <
  36. case 1: //answer as a decimal
  37. cout > a;
  38. cout > b;
  39. cy = a / b;
  40. cout > n;
  41. cout > m;
  42. n = Denom;
  43. m = Num;
  44. for (i = n * m; i > 1; i—)
  45. <
  46. if ((n % i == 0) && (m % i == 0))
  47. <
  48. n /= i;
  49. m /= i;
  50. >
  51. >
  52. cout > a;
  53. cout > b;
  54. q = a / b;
  55. re = (int)a % (int)b;
  56. cout > a;
  57. cout > b;
  58. c = a * (b / 100);
  59. cout > x;
  60. cout > y;
  61. x_to_the_y = pow(x, y);
  62. cout > r;
  63. cout > a;
  64. double pow(double x, double y);
  65. cout > x;
  66. cout > y;
  67. x_to_the_y = pow(x, y);
  68. cout 4 24503

In case 2 try using:

int n, m, i;
n, m, i= 0;

instead of:
int n, m, i = 0;

not sure why it works this way.

Hi,
I think the error is coming becos the n,m declartion in case 2 is clashing with the declartion in the beginning of the program.
Enclose the case 2 inside curly brace like this

Hi,
I don’t know about the tags. I just started today.

The variables defined at the top of the program
are in scope for the duration of the entire program.
So declaring n and m again is not necessary in case 2.
You could declare i at the top of the program and then
you may not have a problem. If you want to keep i local,
it is correct to enclose the contents of the case in curly brackerts. That makes i a local variable for case 2.
It would not hurt to enclose each case in curly brackets and define your local variables for each case, if you would like to. Anyway, whatever is at the top is in scope to the end of the program. C++ allows you to declare
your variables near the applicable code, whereas C does not. So in your case, it would not hurt to take advantage of the capabilities of C++.

case 2: //answer as a fraction
int n, m, i = 0;
etc.
break;
case 3: //answer as a number with a remainder
// error C2360: initialization of ‘i’ is skipped by ‘case’ label
cout Expand | Select | Wrap | Line Numbers

  1. case 2: //answer as a fraction
  2. <
  3. int n, m, i = 0;
  4. >
  5. etc.
  6. break;
  7. case 3: //answer as a number with a remainder
  8. // error C2360: initialization of ‘i’ is skipped by ‘case’ label
  9. cout Message Cancel Changes

Post your reply

Sign in to post your reply or Sign up for a free account.

Источник

Error c2360 is skipped by case label

Please contact us if you have any trouble resetting your password.

Читайте также:  Error in file meshname shape name

case labels are just jump targets; there are no case «blocks» unless you write the block yourself. The reason the restriction you mention exists is best demonstrated with an example:

It is important to remember that a switch/case is just a fancy wrapper for a bunch of gotos and labels. For example, the code above is semantically equivalent to this:

[Edited by — Sharlin on March 24, 2006 6:04:31 PM]

Quote: Form MSDN
the variable is within scope until the end of the switch statement

So it could be used outside the particular case, without initialization, which is unsafe.

Although I’m surprised this (which is basically the same) goes away with a warning only:

Great explanation, thank you. So is it preferred to use blocks for local variables within a case block, or is it best to declare it outside the switch?

Depends on the solution.

Quote: Original post by deffer
Although I’m surprised this (which is basically the same) goes away with a warning only:
*** Source Snippet Removed ***
I guess they (VS team) don’t care much about safety of ‘goto’ users.
[grin]

Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).

Quote: Original post by MaulingMonkey
Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).

Now it’s semanticly the same, but with different treatment from the compiler (VS 7.1).

Quote: Original post by MaulingMonkey
Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).

*** Source Snippet Removed ***

Now it’s semanticly the same, but with different treatment from the compiler (VS 7.1).

In the code you typed, the destructor of B is called but the constructor is not. This is . not ideal.

Basically, always do this:

«Pretend» that code needs <>s after a case statement — even more, «pretend» that code needs
<
>break;
after a case statement.

(there are rare exceptions in which you can skip the break;, but . they should be used about as carefully as you would use a goto statement.)

Источник

Initialization skipped by case label

Hi everyone,
I have worked some more on my code and this time I am getting some error that I am not able to resolve. Please help me.

The error says: «initialization skipped by case label.» Please show me how to resolve this.

Here is the code. The error has a remark in red.

Really appreciate your help.
Thanks.

    4 Contributors 5 Replies 4K Views 7 Hours Discussion Span Latest Post 14 Years Ago Latest Post by robgeek

You error is the fundamental language mistake. It is not possible
to declare any new variable or object in the scope of the switch statement that has outside scope. ifstream input(«help.txt»); is not allowed.
Additionally, you have already declared input at the top
[4 lines below main()].

To open an output stream it is output.open(«ParkingCharges.txt»,ios::out); NOT: ofstream.output(«Parking Charges.txt», ios::out); Because you are using a class name not an instance/object (ofstream is not an object) and you are using output which is not in the class or the public base classes.

All 5 Replies

You error is the fundamental language mistake. It is not possible
to declare any new variable or object in the scope of the switch statement that has outside scope. ifstream input(«help.txt»); is not allowed.
Additionally, you have already declared input at the top
[4 lines below main()].

Читайте также:  Pip install mysql error command errored out with exit status 1

If you want to try this

Further, you don’t actually use input and output, but define a NEW
instance of output in the function CarParking.

Источник

Compiler errors C2300 Through C2399

The articles in this section of the documentation explain a subset of the error messages that are generated by the compiler.

The Visual Studio compilers and build tools can report many kinds of errors and warnings. After an error or warning is found, the build tools may make assumptions about code intent and attempt to continue, so that more issues can be reported at the same time. If the tools make the wrong assumption, later errors or warnings may not apply to your project. When you correct issues in your project, always start with the first error or warning that’s reported, and rebuild often. One fix may make many subsequent errors go away.

To get help on a particular diagnostic message in Visual Studio, select it in the Output window and press the F1 key. Visual Studio opens the documentation page for that error, if one exists. You can also use the search tool at the top of the page to find articles about specific errors or warnings. Or, browse the list of errors and warnings by tool and type in the table of contents on this page.

Not every Visual Studio error or warning is documented. In many cases, the diagnostic message provides all of the information that’s available. If you landed on this page when you used F1 and you think the error or warning message needs additional explanation, let us know. You can use the feedback buttons on this page to raise a documentation issue on GitHub. If you think the error or warning is wrong, or you’ve found another problem with the toolset, report a product issue on the Developer Community site. You can also send feedback and enter bugs within the IDE. In Visual Studio, go to the menu bar and choose Help > Send Feedback > Report a Problem, or submit a suggestion by using Help > Send Feedback > Send a Suggestion.

Читайте также:  Что такое error x1507

You may find additional assistance for errors and warnings in Microsoft Learn Q&A forums. Or, search for the error or warning number on the Visual Studio C++ Developer Community site. You can also search Stack Overflow to find solutions.

For links to additional help and community resources, see Visual C++ Help and Community.

Источник

Error c2360 is skipped by case label

PRF
Дата 7.9.2008, 18:22 (ссылка) | (нет голосов) Загрузка .

Шустрый

Профиль
Группа: Участник
Сообщений: 135
Регистрация: 13.10.2007

Репутация: нет
Всего: нет

Здравствуйте.. помогите пожалуйста, выдает почему то ошибку, вроде бы простой код, может я чего то не замечаю?

Код
do
<
key = _getch();

switch(key)
<
case ‘1’:
/* ввод количества вершин */
crus(«Введите количество вершин: «);
int N;
cin >> N;

/* ввод матрицы смежности */
crus(«Введите матрицу смежности: «);
list** matrix = new list*[N — 1];
list** first = new list*[N — 1];
break;
case ‘2’:

break;
>
>
while(key != 27);

выдает такую ошибку

error C2360: initialization of ‘first’ is skipped by ‘case’ label
error C2360: initialization of ‘matrix’ is skipped by ‘case’ label

помогите пожалуйста, вроде бы конструкция switch правильно использована..

vinter
Дата 7.9.2008, 18:27 (ссылка) | (нет голосов) Загрузка .

Explorer

Профиль
Группа: Завсегдатай
Сообщений: 2735
Регистрация: 1.4.2006
Где: Н.Новгород

Репутация: 13
Всего: 56

Код
do
<
key = _getch();

switch(key)
<
case ‘1’:
<
/* ввод количества вершин */
crus(«Введите количество вершин: «);
int N;
cin >> N;

/* ввод матрицы смежности */
crus(«Введите матрицу смежности: «);
list** matrix = new list*[N — 1];
list** first = new list*[N — 1];
break;
>
case ‘2’:

break;
>
>
while(key != 27);

Lazin
Дата 7.9.2008, 18:31 (ссылка) | (нет голосов) Загрузка .

Эксперт

Профиль
Группа: Завсегдатай
Сообщений: 3820
Регистрация: 11.12.2006
Где: paranoid oil empi re

Репутация: 41
Всего: 154

Код
.
case 1:
<
int var1;
>
bread;
case 2:
<
int var2;
>
.

Это сообщение отредактировал(а) Lazin — 7.9.2008, 18:32

PRF
Дата 7.9.2008, 20:41 (ссылка) | (нет голосов) Загрузка .

Шустрый

Профиль
Группа: Участник
Сообщений: 135
Регистрация: 13.10.2007

Репутация: нет
Всего: нет

спасибо большое! раньше не знал этого момента(((

Это сообщение отредактировал(а) PRF — 7.9.2008, 20:41

Опытный

Профиль
Группа: Участник
Сообщений: 722
Регистрация: 30.3.2006

Репутация: 27
Всего: 32

UnrealMan
Дата 7.9.2008, 21:47 (ссылка) | (нет голосов) Загрузка .
Цитата(Lazin @ 7.9.2008, 19:31 )
между кейсами нельзя объявлять переменные

Объявлять можно, инициализировать нельзя.

Это сообщение отредактировал(а) UnrealMan — 7.9.2008, 21:48

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ 🙂
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе — для этого существует «Центр Помощи».
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »

[ Время генерации скрипта: 0.1165 ] [ Использовано запросов: 21 ] [ GZIP включён ]

Источник

Оцените статью
toolgir.ru
Adblock
detector