Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

global variable in function file

Name: Anonymous 2012-06-03 18:50

Ok, very novice programmer here. This is part of one of my first programs just dicking around. Basically, I want this program to say "How may I serve you?" the first time the "menu" comes up and then "May I do anything else?" afterwards. With "bool runOnce = false" is inside the function, obviously it will be reset to false every time the function is called so the program will always print "How may I serve you". Making it global within this file fixes that issue ... but I get the feeling that's bad programming. I mean it's not really a global variable I don't think, since it can't be accessed by any other part of this program. But, it would be global to anything else that would go in this file if the program became much more complicated.

Can anyone think of a better way to tackle the "Do this1 the first time, do this2 all subsequent times" problem?

#include<iostream>
#include"menu.h"

bool runOnce = false;

int menu()
{
    int choice = 0;
   
    if (runOnce == false)
    {
        std::cout << "How may I serve you?" << std::endl;
        runOnce = true;
    } else
    {
        std::cout << "May I do anything else?" << std::endl;
    }
    std::cout << std::endl;

    std::cout << "(1) Make me a sandwich." << std::endl;
    std::cout << "(2) Give me a blowjob." << std::endl;
    std::cout << "(3) Nothing, go away." << std::endl;
    std::cout << "\n: ";
    std::cin >> choice;
    return choice;
}

Name: Anonymous 2012-06-03 21:06

static?

Name: Anonymous 2012-06-03 21:18

>>2
Hey, thanks! I looked up what a static variable was and how to use it and it worked in my program.

Can anyone tell me what you would call runOnce in the OP code? It's certainly not global to the whole program. Would you just say that it's global within the scope of everything contained within menu.cpp or what?

Name: Anonymous 2012-06-03 22:09

I was going to say this is why Sepples is a poor choice of language for a beginner (because it's huge and hideous), but the problem here is actually that you didn't even bother to read a fucking book before you decided to bother other people.

Name: Anonymous 2012-06-03 23:05

>>4
that isn't really a problem, just a something that happens to irritate you as a consequence.

Name: Anonymous 2012-06-04 10:53

>>4
I'm working my way through a text. Hadn't covered static variables yet. Forgive me for overstepping my bounds and asking a question without really doing me homework. I'll wait until I've finished the book before I ask anything else.

Don't change these.
Name: Email:
Entire Thread Thread List