0

Why does C language acts like this

#include <stdio.h> 
#include <stdlib.h> 
int main()
{
 const int size = 3;
 double a[size];
 for(int n=0; n<size; ++n){
   a[n] = n;
   printf("%d,%d\n",n,n+1);
 }
}

Output is

0,1 
1,2 
2,3

But When i do this

#include <stdio.h> 
#include <stdlib.h> 
int main()
{
 const int size = 3;
 double a[size];
 for(int n=0; n<size; ++n){
   a[n] = n;
   printf("%d,%d\n",a[n],n+1); //change is here
 }
}

Output is :

1,1
2,2
3,3

Why does the value changes just by replacing n and a[n] which are same?

aniket dhole
  • 91
  • 1
  • 7

3 Answers3

6

a[n] is a double, which you can’t printf with %d

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
1

The reason is due to the fact in the second you are trying to print a[n] which is a double using %d format specification, which is for int, resulting in undefined behavior.

For example, in my system I get this printed:

1,1559556488
2,1559554816
3,1559554816

The compile should be warning you about this. C-lang gives you one:

clang-7 -pthread -lm -o main main.c
main.c:9:21: warning: format specifies type 'int' but the argument has type
      'double' [-Wformat]
   printf("%d,%d\n",a[n],n+1); //change is here
           ~~       ^~~~
           %f
1 warning generated.
norok2
  • 25,683
  • 4
  • 73
  • 99
1

"Why does the value changes just by replacing n and a[n] which are same"

When you using printf("%d,%d\n", a[n], n+1); in the second example, the second argument (a[n]) is of type double, whereas in the first example n is of type int.

That you use n of type int as index doesn't make the addressed double object of type int.


To use the %d conversion specifier to print a double value invokes undefined behavior.

The C standard states:

d,i The int argument is converted to signed decimal in the style[-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.

Source: C18, 7.21.6.1/8

and

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

Source: C18, 7.21.6.1/9