0

I have created a pointer to a structure, the structure contains a single data member of type int. Whenever I print the data member without initializing the pointer if it is int or long it is always printing 1 if I set it to double it prints random values.

  #include<iostream>

  using namespace std;

  struct node {
       int data ;
   };

  int main() { 
   struct  node a ;
   struct  node *c ;
   cout << a.data << endl ;
   cout << c -> data << endl ;
  }

I am using g++ to compile on Ubuntu.

  • 5
    It is undefined. It just happens to be `1` today. – Weather Vane Apr 15 '20 at 17:40
  • 2
    And your question is? Printing uninitialised data is an example of *undefined bahviour* and both the situations you describe are consistent with undefined behaviour. – john Apr 15 '20 at 17:40
  • Any value is possible, don't rely on what value appears to in the data when you test. There is no guarantee. – drescherjm Apr 15 '20 at 17:44
  • 2
    Undefined behaviour is the most frightening thing in any programming language. One of the infinite possible results is it looks like reasonable output. You will come to appreciate crashing programs. At least you know they are wrong. – user4581301 Apr 15 '20 at 17:44
  • ***One of the infinite possible results is it looks like reasonable output.*** That is the worst. When it looks like the answer is correct however UB is hiding from you. – drescherjm Apr 15 '20 at 17:45
  • `init b ;` ?!? Details do matter, a single character can make the difference between correct code and code that does "weird stuff" like yours. – 463035818_is_not_a_number Apr 15 '20 at 17:46
  • No, it is always 1 when the data member is of type int or long int but when the data member is double or float it prints some garbage value. – user8245171 Apr 15 '20 at 18:04
  • What happens when you use a different compiler on a different OS. I expect it not to have this value. – drescherjm Apr 15 '20 at 18:14
  • I am using g++ on Ubuntu, I tried online compiler ( https://www.onlinegdb.com/online_c++_compiler) and it is giving segmentation fault. So then is it the problem of g++ only? – user8245171 Apr 15 '20 at 18:30
  • 1
    That is what undefined behavior is about, once you have UB the result of your program is meaningless. Your calculated values may or may not be correct. It may work on one system today and fail tomorrow. It may work for years then fail suddenly after a security update to a seemingly unrelated system file. – drescherjm Apr 15 '20 at 19:13
  • 1
    I always wonder how many times [this demonstration](https://www.youtube.com/watch?v=73wMnU7xbwE) worked perfectly before Bill "The Richest Dude on the Planet" Gates agreed to be on stage for the presentation. Not a good time for UB to manifest. – user4581301 Apr 15 '20 at 20:29

0 Answers0