-1

Why i am getting the different values of i.

#include <stdio.h>
void pri(int,int);
int main()
{
    float a=3.14;
    int i=99;
    pri(a,i);
    getch();
}
void pri(int a,int i)
{
    printf("a=%f i=%d\n",a,i);
    printf("i=%d a=%f\n",i,a);
}
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
Tushar Gaurav
  • 486
  • 4
  • 18

2 Answers2

3

You declared a as an int, but you are using %f so it should be declared as a float:

void pri(float a, int i)
{
    printf("a=%f i=%d\n", a, i);
    printf("i=%d a=%f\n", i, a);
}

If you have an incorrect type you get undefined behaviour. The specification for printf reads (7.19.6.1 paragraph 9):

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Emphasis mine.

Source

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • ya i know that's the correction for dis program.....but i am not getting why both consecutive printf statements giving different values of i. – Tushar Gaurav Sep 27 '12 at 08:23
  • @TusharGaurav: Because as you can see from my edit, it's specified as **undefined behaviour**. Anything can happen when you invoke UB, including incorrect results being displayed. – Mark Byers Sep 27 '12 at 08:37
0

to explain your comment's question:

printf("a=%f i=%d\n", a, i);

will evaluate to something like:

printf("a=");
printf(/*next arguments up to size of float*/ a, i);
printf(" i=");
printf(/*...decimal*/ /*whatever is on the stack, because a and i are already consumed*/);

you can rescue your function with: 'printf("a=%f i=%d\n", (float)a, i);'

Peter Miehle
  • 5,984
  • 2
  • 38
  • 55