Garhve R
Garhve R

Reputation: 31

Why is the default case matched in this switch statement?

I've got a question about switch statements. Here is my code:

#include<stdio.h>
int main()
{
  float a=0.0f;
  float b=0.0f;
  char operation=0;

  printf("Enter expression:");
  scanf("%f %c %f",&a,&operation,&b);

    switch(operation)
    {
      case '+':
      printf("=%.2f\n",a+b);
      break;

      case '-':
      printf("=%.2f\n",a-b);
      break;

      case '*':
      printf("=%.2f\n",a*b);
      break;

      case '/':
      if(b==0)
      printf("\ndivision by zero error.\n");
      else
      printf("=%.2f\n",a/b);
      break;

      case '%':
      if(b==0)
      printf("\ndivision by zero error.\n");
      else
      printf("=%d\n",(int)a%(int)b);
      break;

      default:
      printf("invalid operation\n");
      break;
    }
    return 0;
}

And this is result about two different input, one right, one wrong.

my output

Why, when I enter two letters instead of two numbers, does it go into the default case?

Upvotes: 2

Views: 161

Answers (3)

pmg
pmg

Reputation: 108968

Because you need to check the return value of scanf

// scanf("%f %c%f", &a, &operation, &b);
if (scanf("%f %c%f", &a, &operation, &b) != 3) {
    fprintf(stderr, "Unable to convert input!\n");
    exit(EXIT_FAILURE);
}

Upvotes: 1

Ardent Coder
Ardent Coder

Reputation: 3985

scanf("%f %c %f",&a, &operation, &b);

So, when you enter a+b:

  1. 'a' is not a float

  2. scanf fails (you can check this by looking at its return value)

  3. operation is still with its default value which is 0

Inside the switch statement, none of the cases('+', '-', '*', '/', '%') get matched because char operation = 0;

Therefore, the default block is executed.

Upvotes: 2

Eraklon
Eraklon

Reputation: 4288

a+b won't match the format string of your scanf since it expects floats not chars (like a or b), therefore scanf does not do anything.

scanf returns the number of items it was able to read which will be 0 in this case. Checking its return value is not a bad idea.

And since operation is initialized to 0 the default case will execute.

Upvotes: 3

Related Questions