0
#include<>
int calc(int,int,char);
void main()
{
    int a,b;
    char c;
    printf("enter 2 nos");
    scanf("%d%d",&a,&b);
    printf("enter op");
    scanf("%s",&c);
    printf("the ans is %d\n",calc(a,b,c));
}
int calc(int a,int b,char c)
{
    int ans;
    switch(c)
    {
        case'+':ans=a+b;break;
        case'-':ans=a-b;break;
    }
    return ans;
}

why does this program give the output as b...it works when i give a, b and c as global variables...what change should i do if i want them as local variables...using functions

Bill Lynch
  • 72,481
  • 14
  • 116
  • 162
  • See [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/) for why `void main()` is generally not a good idea. – Jonathan Leffler Feb 28 '16 at 08:14

2 Answers2

2

scanf("%s",&c); causes undefined behavior. You are storing at least two characters ['+', '\0'] and you have only allocated space for one.

You might consider scanf(" %c", &c);. Note that I intentionally added a space in the format string to eat any whitespace that the user might include.

Bill Lynch
  • 72,481
  • 14
  • 116
  • 162
0
char c;
...
scanf("%s",&c);

Is plain wrong, even if c is a global variable.

Your scanf will take input from the keyboard and store the string you type at the address given as second parameter (in your case the address of c). But c has only space for a single character, and your string inputted with scan will take at least 2 characters (the one you type and th terminating zero).

In your case you get undefined behaviour, which means that your program may

  • appear to work
  • crash each time you run it
  • appear to work with a certain string you type, and crash with another
  • or any other odd behaviour

You need this:

char c[10];
...
scanf("%9s",c);
...
printf("the ans is %d\n",calc(a,b,c[0]));

which lets allows you to input a string of length 9 (9 characters + terminating zero = 10).

Jabberwocky
  • 40,411
  • 16
  • 50
  • 92