"goto" statement

Use "goto" statement to return to the code marked above, and the marked "scanf" statement will not be executed again. How to solve this problem?
I want "scanf" to execute again instead of skipping it, resulting in a constant loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  Put the code you need help with here.
while (x != a)
	{
	label:int i = scanf_s("%d", &x);
		if (i == 1)
		{
			if (x > a)
			{
				printf("biger\n");
				n++;
			}
			if (x < a)
			{
				printf("smaller\n");
				n++;
			}
		}
		else
		{
			x = 0;
			goto label;
		}
	}
Last edited on
Who's telling you to use goto?

Newbies shouldn't be anywhere near needing to use goto.
Much less gotos which jump backwards in the code - that's what loops are for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
while (x != a)
{
	int i = scanf_s("%d", &x);
	if (i == 1)
	{
		if (x > a)
		{
			printf("biger\n");
			n++;
		}
		if (x < a)
		{
			printf("smaller\n");
			n++;
		}
	}
	else
	{
		int ch;
		while( (ch=getchar()) != EOF && ch != '\n') ;
	}
}

This will loop just fine until the user manages to guess the value of a.
No messy goto required.
It looks like your label needs to be after

int i = scanf_s("%d", &x);

and before:

if (i == 1)

In this code sample goto statement is bad, there are cases where goto makes code more clear.

The rules as to when use to use goto is this:
if goto statement would skip initialization of any variables, then it should not be used.

if goto statement jumps back in execution it should "probably" not be used.

if goto statement is used to jump forward with the goal to normaly exit current function it's perfectly valid if that makes the code more readable or it takes less boilerplate code to write.

also a general rule is, the goto is more dangerous the more labels there are.
that is more labels is more dangerous than more goto statements.

Knowing that, who ever told you to use goto in this sample code is giving you a bad sample as to when and how to use goto.

EDIT:
Btw. be aware of people who tell that goto should never be used.
goto is a valid and useful language feature, saying it should absolutely never be used is wrong.

There are cases where goto is good, but these cases are very rare, you can find plenty of examples online where goto is good and sample where it is bad.
Last edited on
the marked "scanf" statement will not be executed again
Oh it executes, it just keeps failing. After all, if it fails once then it won't read offending characters. That means the next time you call it, it just tries to read the same character and fails again. Line 20 of Salem C's post skips the rest of the input line so that the next call to scanf() will hopefully try to read the next number.
Topic archived. No new replies allowed.