0

I'm a little bit confused. As far as I know, if you declare uninitialized variable in C, so its value is indeterminate.

If you don’t initialize an variable that’s defined inside a function, the variable value remain undefined.That means the element takes on whatever value previously resided at that location in memory.

If I applied ^(XOR) operator to uninitialized integer variable itself. Like,

#include <stdio.h>

int main()
{
        int a;
        printf("%d\n", a^a);
}

it's clear that a^a should be zero because the result is zero only when we have two zeroes or two ones. So, I have a question : Is it undefined behaviour?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
msc
  • 33,420
  • 29
  • 119
  • 214
  • see also [(Why) is using an uninitialized variable undefined behavior in C?](http://stackoverflow.com/q/11962457/995714) – phuclv Mar 16 '17 at 06:19
  • its undefined behavior only when `a==a` ... oh wait, that's UB also. – technosaurus Mar 16 '17 at 06:20
  • [Value of int i = i ^ i ; Is it always zero or undefined behavior?](http://stackoverflow.com/q/17485814/995714) – phuclv Mar 16 '17 at 07:15

2 Answers2

1

Yes, this is undefined behaviour.

Attempt to use a variable with indeterminate value which

  • can have trap representation
  • not have it's address taken

will cause undefined behavior.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Yes it's undefined behavior. Just declaring and not initializing the variable, stuff the variable with a garbage value .

Shrey
  • 98
  • 1
  • 12
  • `Performing xor on a value with itself gives 0 . It's undefined behavour.` isn't that contradictory? If you have a defined value, how is it UB? – Sourav Ghosh Mar 16 '17 at 06:25
  • @SouravGhosh , Sorry I guess my answer is a bit confusing . They are two distinct statements . – Shrey Mar 16 '17 at 06:36
  • That was the point for the comment, please refine the answer and thanks for your efforts, :) – Sourav Ghosh Mar 16 '17 at 06:36