Thread: Structure variable not working inside main

  1. #1
    Registered User
    Join Date
    Jan 2019
    Posts
    1

    Question Structure variable not working inside main

    Following is the simple program for sum using structure.
    Code:
    #include<iostream>
    #include<string.h>
    
    using namespace std;
    
    struct ab
    {
        int x,y;
    }dd;
    void sum()
    {  cin>> dd.x>>dd.y;
     int z=    dd.x + dd.y;
     cout<<z;
    }
    int main()
    {
        sum();
        return 0;
    }
    I am facing a problem when I declare structure variable "dd" outside of main with structure then the programme works but if declared within main, it does not . Can anyone tell me why it is so ?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    but if declared within main, it does not .
    Post your code illustrating the problem. The code you posted should work because you're using a horrible global variable.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    On the face of it, it could be something as simple as you need to pass the local variable as a parameter to sum().

    Code:
    void sum(ab &dd)
    {
        cin>> dd.x>>dd.y;
        int z=    dd.x + dd.y;
        cout<<z;
    }
    int main()
    {
        ab dd;
        sum(dd);
        return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 03-18-2014, 10:43 AM
  2. Replies: 16
    Last Post: 09-04-2013, 10:09 AM
  3. assign string to the string variable inside structure!
    By king_zart in forum C++ Programming
    Replies: 20
    Last Post: 12-09-2012, 11:37 AM
  4. printf not working inside main scope
    By Brownman in forum C Programming
    Replies: 3
    Last Post: 08-03-2009, 12:35 AM
  5. Replies: 12
    Last Post: 10-14-2003, 10:17 AM

Tags for this Thread