struct redeclare problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • prads
    New Member
    • Oct 2007
    • 25

    #1

    struct redeclare problem

    hello,
    i have a struct and have declared it as shown below. If i print its value in the main() fn it prints it correctly.Howev er if i declare the struct again in the main() and try to print its value it doesnot give me the correct value but prints some garbage value. Why is it so? Is there any way to correct it because i think i have to declare it again in main() for initializing other variables.
    thanks,
    prads

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstring>
    #include <cmath>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    struct set
    {
           long int mstoprocess;
           int noofchannels;
           int skipnoofbytes;
    }settings={37000,8,0};
    int main()
    {
        int i;
        static struct set settings;  //if this is removed it works fine!!!!
     cout<<settings.mstoprocess<<endl;
    getchar();
    return 0;
    }
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    prads, I’ll answer your question. But I notice that you tend to write with a mix of C and C++ code. Now, it’s fine to use C libraries in C++, but you can’t just use C syntax with C++. One example would be structs, where the C++ syntax differs from C. If you want to use C, use C. If you want to use C++, use C++. The languages are different.

    If you are having trouble sticking to one language, it suggests that you don’t have access to a good learning resource. Ideally, you should get a C++ book like C++ Primer by Lippman or Accelerated C++ by Koenig. Those are beginner level books that are also accurate. Most aren’t. If you can’t get either of those books for whatever reason, rely on cprogramming.co m or cplusplus.com as they have accurate tutorials. Google for C FAQ and C++ FAQ. Much of the information there is extremely valid as well.

    As to your actual question. First, if you have declared and defined struct set before main, then you do not have to declare it afterwards. The declaration is pointless. Hence, your declaration in main is useless.

    Second, not only do you declare struct set, but even worse, you create a local variable settings. The settings created in main takes precedence over the global variable settings. However, your local variable settings does not have its member variables initialized to anything. Hence you’ll get “garbage” which in reality is whatever random crud exists in the memory locations for those variables.

    The concepts involved in understanding this behavior are: why one initializes variables, and local and global scopes. If you do not understand those topics, you do not have the necessary knowledge to understand the behavior of your code.

    Comment

    Working...