Thread: memory ?

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    25

    Question memory ?

    I'm new to C++ so first programs naturally include a calculator.
    My memory question is this:
    I have a function for each math procedure(add, sub, mul, div,etc)
    I have globally declared double a, b, ; for use with all the functions. I have read many places to keep the scope of variables as small as possible...So do the values of a, b, accumulate in memory by declaring them globally?.....ie :
    0x00001 = a for first function
    0x00002 = b for first function
    0x00003 = a for second function
    0x00004 = b for second function
    or would they over write each other therefore using the same memory space??
    A little confused by this ........appreciate any thoughts.....:^)

  2. #2
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Don't declare variables globally. You should declare your variables a and b in the main() function. At the end of the main function, the memory set aside for a and b will be given back to the computer. Look up the reserved words auto, static, and register.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    78
    when you assign something to the variable it overwrites the previous value... You might want to try not using globals for example...


    Code:
    #include <stdio.h>
    
    double add(double a,  double b)
    {
        return a+b;
    }
    
    int main()
    {
        double x = 25.367, y = 86.254;
    
        printf("%.3f + %.3f = %.3f\n", x, y, add(x, y));
        return 0;
    }

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    25

    Thumbs up Re: mem?

    joshdick & Rog
    Thanks for your replys.........
    I looked up those keywords and the info on static answered my question. Thanks again.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-13-2008, 02:14 AM
  2. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  4. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM
  5. What's the best memory (RAM) type?
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 12-15-2001, 12:37 AM