开发者

Switch: Declared Variable outside switch and use it in it

The following isn't the it's just the part causing problem:

int s,p;
        scanf("%d",s);
switch(s)
{
    case 1:
    {
    p=10;
    break;
}
case 2:
    {
    p=15;
    break;
}
}
printf("%d",p);

The problem is that p prints a random and very large number, What is causing it?

So i used some of your advice and know i have the following code:

int s,p=0;
        scanf("%d",&s);
switch(s)
{
    case 1:
    {
    p=10;
    break;
}
case 2:
    {
    p=15;
    break;

}
default:
{
    printf("Number invalid");
    return 0;
}
}
printf("%d",p)开发者_运维问答;

Now i it's always going to default even though i only enter 1 or 2

Ok now it worked Thank You All!


You have two problems: (i) p is uninitialised and (ii) you're passing s to scanf where the address of s is required.

Change:

int s,p;
scanf("%d",s);

to:

int s, p = 0;
scanf("%d", &s);


"int p" declaration assigns p to an arbitrary value: whatever happened to be in memory. Now, if s doesn't equal 1 or 2, that value never changes, and that's what you see. What you can do is

  • add default: clause to your switch() and assign p to something meaningful there
  • declare p as "int p = 0;"


What number are you scanning in? You probably you don't have a switch case for that number, which means that p is uninitialized (and hence random). For example if you enter 3, there is no case statement for 3 and p will contain a random value. I would suggest that you detect invalid input with an default case where you assign a value of 0 to p.

default:
    p = 0;

Corrected code:

int s,p;
scanf("%d", &s);

switch(s)
{
    case 1:
    {
        p=10;
        break;
    }
    case 2:
    {
        p=15;
        break;
    }

    default:
    {
        p=0;
        break;
    }
}
printf("%d",p);

Edit: Fixed scanf problem per Paul R


You can use default and then try to figure out what was scanned in

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜