-1

I was playing around with bool variables. I am aware that boolean is used to represent a true (any other number besides 0) or false (the number 0). I realized that the variables create random integer numbers. I was wondering if one can one use boolean variables to generate random numbers? Can someone please elaborate on this behaviour caused by the keyword boolean?

My code is as follows:

  #include<stdio.h>
  #include<stdbool.h>

  int main()
 {
  bool a,b,c,d,e,f,g,h,i,j,k;

   printf("%d\n",a);
   printf("%d\n",b);
   printf("%d\n",c);
   printf("%d\n",d);
   printf("%d\n",e);
   printf("%d\n",f);
   printf("%d\n",g);
   printf("%d\n",h);
   printf("%d\n",i);
   printf("%d\n",j);
   printf("%d\n",k);
 }

2 Answers2

4

This is not behaviour specific to a bool. This is caused because you are using an uninitialized variable. This is not only not random, it is not safe. This is undefined behaviour, you should avoid it at all costs.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Per the C standard, the values of uninitialized objects are indeterminate. This does not necessarily lead to undefined behavior. – Eric Postpischil Nov 16 '17 at 13:15
  • For example, `unsigned char x; printf("%d %d", x, x);` must print the same number twice. If the behavior were undefined according to the C standard, this could print two different values or crash. But the behavior is not undefined; it behaves as if `x` has some value. – Eric Postpischil Nov 16 '17 at 14:36
  • @EricPostpischil Do you have the reference? I thought it was undefined, same as the c++ standard? – Fantastic Mr Fox Nov 20 '17 at 05:19
  • C 2011 [N1570] 6.7.9 10 says that uninitialized objects with automatic storage duration have indeterminate values. But I had forgotten 6.3.2.1 2, which says, if the address of the object is not taken, the behavior is undefined. Thus, inserting an otherwise unused `&x;` suffices to make the behavior defined, since it takes the address of `x`. – Eric Postpischil Nov 22 '17 at 14:47
0

Boolean is not randomly defined. These variables take false as default value. In compiler. The default value is consistent rather than random 0 or 1 from time to time.

Jerry213
  • 81
  • 1
  • 10
  • Actually they do not take any value as a default value. In most implementations it is whatever the value is in the memory where the bool is made. It could be 0 or anything else. It is only set to a default when it is declared global or static. – Fantastic Mr Fox Nov 16 '17 at 02:16
  • I think they do, maybe some languages do have 0 to anything, but some only do have 0 and 1, VB has a boolean value of 0 and 1. If you consider SQL Server's bit as a boolean value, it also has 0 and 1 – Mr.J Nov 16 '17 at 02:20
  • Per C 2011 (N1570) 6.7.9 10: “If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.” – Eric Postpischil Nov 16 '17 at 12:53