Home > Blockchain >  default values for long datatype in c programming
default values for long datatype in c programming

Time:11-06

I am trying to add two long variables with default values. But one of the variable is getting assigned to value 1. But As per my knowledge it should get assigned with 0. why it was happening?

#include <stdio.h>

long add(long, long);

main()
{
    long xno;
    long zno;
    long sum;

    printf("xno = %d, zno = %d \n", xno, zno);

    sum = add(xno, zno);

    printf("sum = %d", sum);
}

long add(long x, long y) {
    printf("x = %d, y = %d \n", x, y);
   return x   y;
}

result: 
xno = 0, zno = 1
x = 0, y = 1
sum = 1

result

CodePudding user response:

Objects with automatic storage duration are not initialized by default. The C standard specifies they have “indeterminate” value, which means they do not have any fixed value. Essentially, it means your program is broken.

In a program where the objects had been initialized or had been assigned values, the compiler would manage their values properly: If it needed the value of xno and did not have it in a processor register already, the compiler would generate a load instruction to bring it into a register. If it had it in a register, it would use that register for the value of xno. So, in a working program, the compiler generates appropriate instructions.

What you are seeing is that, since xno and zno were never initialized or assigned values, the compiler is omitting the instructions that would load their values. Instead of filling a register with the value loaded from memory, the program executes using whatever data was in the register from some prior use. Further, the register the compiler uses for that may be different each time xno or zno is used. So a program could behave as if it is using different values for xno and zno each time they are used.

Further, in some circumstances, the C standard specifies that using an uninitialized automatic object has undefined behavior. (This occurs when the address of the object is never taken.) In this case, the C standard not only does not specify what value the object has, it does not specify what the behavior of the program is at all.

CodePudding user response:

There is no default value for non static local variables in the c language. You can think of having a non fixed 'random garbage value' for those declared variables. Also, in printf for printing long you should use %ld rather than %d

  •  Tags:  
  • c
  • Related