LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices



Reply
 
Search this Thread
Old 02-09-2003, 11:25 PM   #1
PTBmilo
Member
 
Registered: Jan 2003
Posts: 167

Rep: Reputation: 30
question about scope in c++


I'm having trouble understanding what is going on with the whole issue of scope in c++. I am writing a program to calculate the velocity of an aircraft depending on some input. I don't want to have global variables, but whenever I put them all in main(), g++ tells me that they are undeclared when they show in the rest of the functions.

This works:

double x,y,z;
int a();
int b();

int main () {
<code>
a();
b();
}

int a(){
x=1
}
int b(){
y=2
}

###########################

but this doesn't:

int main(){
double x,y,z;
int a();
int b();

a();
b();
}
int a(){
x=1
}
int b(){
y=2
}

What's going on here? Does it have to do with the prototypes? I've tried all kinds of different placements, but can only get the top style to work.

Can somebody help me out? I can post the entire code if you want.
 
Old 02-10-2003, 01:07 AM   #2
GtkUser
Member
 
Registered: Sep 2002
Location: Canada
Distribution: Redhat 9.0
Posts: 637

Rep: Reputation: 30
Here is one variant. You needed to place your prototypes outside of any code blocks but the local variables should be inside code blocks.

Code:
//prototypes
int MyFunction();

int main()
{
  //variables defined in main
  int num;

  //function call
  num = MyFunction();
  return 0;
}

//function definition
int MyFunction()
{
  return 10;
}
 
Old 02-10-2003, 01:43 AM   #3
PTBmilo
Member
 
Registered: Jan 2003
Posts: 167

Original Poster
Rep: Reputation: 30
Ok, I tried putting the prototypes outside of the main function, but it still doesn't work. I see the method that you suggest, but I really can't use that at this point in the class.... my teacher will actually TAKE OFF points... he's really trying to get us to use his EXACT style for now (which sucks because I'm taking another c++ class at the same time)

So am I correct in assuming that you must actually declare the variables outside of the main function for them to be global? I know you end up getting around this with pointers, and pass by value or whatever, but we're not there yet, and I haven't had time to investigate too much on my own.

I just thought that if you declare a variable in a block, that all functions called from that block can access them, but I guess that's wrong

Thanks again for the suggestion.
 
Old 02-10-2003, 01:47 AM   #4
PTBmilo
Member
 
Registered: Jan 2003
Posts: 167

Original Poster
Rep: Reputation: 30
PS:

Here's what DOESN'T work

Code:
#include<iostream>
#include<cmath>
using namespace std;

const double K              = 1.4;
const double ROE            = 0.002378;
const double PSI_2_PSF_CONV = 144;      /* (12in/ft)*(12in/ft) */


int psi2psf();       /* Converts input to pounds/(square foot) units */
int evaluate();      /* Calculates the equasion */
int outputResults(); /* Output the results */


int main()
{
        
double  feetPerSecond, 
        milesPerHour,
        totalPressure_psi,   /* total pressure input...pounds/(square inch) */
        totalPressure_psf,   /* total pressure in terms of square feet */
        staticPressure_psi,  /* static pressure input... pounds/(square inch) */
        staticPressure_psf;  /* static pressure in terms of square feet */
        
        
        
        cout << "\nEnter the Total Pressure in psi: ";
        cin  >> totalPressure_psi;
        cout << "\nEnter the Static Pressure in psi: ";
        cin  >> staticPressure_psi;
        
        staticPressure_psi += .000000000001; /* quality control */
        
        psi2psf();
        evaluate();
        outputResults();        

return 0;
}

int psi2psf ()
{
        totalPressure_psf  = totalPressure_psi  * PSI_2_PSF_CONV;
        staticPressure_psf = staticPressure_psi * PSI_2_PSF_CONV;

return 0;
} 
int evaluate ()
{       /* local variables... for computing only (see top) */
        double  val1,
                val2,
                val3,
                velocitySquared; /* code-cleaner... gimme that memory! :) */
        
        val1 = (2*K*staticPressure_psf)/((K-1)*ROE);
        val2 = ((totalPressure_psf - staticPressure_psf)/staticPressure_psf) \
                + 1;
        val3 = (K-1)/K;
        
        velocitySquared = val1 * ( pow(val2,val3) - 1 ); 
        
        feetPerSecond = sqrt(velocitySquared);

        milesPerHour = (feetPerSecond * pow(60,2))/5280;  /* ft/sec -> mi/hr */

return 0;
}

int outputResults() /* extremely watered down */
{
        cout.setf(ios::fixed | ios::showpoint); /* Show decimal point */
        cout.precision(1);                      /* Print correct accuracy */
             <<"***************OUTPUT**************RESULTS******************\n"

return 0;
}
######################################################
and here's what I get from g++:

Code:
/home/milo/ENG_38/dev [244]> g++ -o lab_2 lab_2.cpp
lab_2.cpp: In function `int psi2psf()':
lab_2.cpp:59: `totalPressure_psf' undeclared (first use this function)
lab_2.cpp:59: (Each undeclared identifier is reported only once
lab_2.cpp:59: for each function it appears in.)
lab_2.cpp:59: `totalPressure_psi' undeclared (first use this function)
lab_2.cpp:60: `staticPressure_psf' undeclared (first use this function)
lab_2.cpp:60: `staticPressure_psi' undeclared (first use this function)
lab_2.cpp: In function `int evaluate()':
lab_2.cpp:79: `feetPerSecond' undeclared (first use this function)
lab_2.cpp:81: `milesPerHour' undeclared (first use this function)

Last edited by PTBmilo; 02-10-2003 at 01:53 AM.
 
Old 02-10-2003, 02:25 AM   #5
PTBmilo
Member
 
Registered: Jan 2003
Posts: 167

Original Poster
Rep: Reputation: 30
OK, I got it. the {BLOCKS} send the variable to it's children, but not the functions. I ended up doing these:

Code:
int evaluate(double& totalPressure_psf, double& staticPressure_psf,
             double& feetPerSecond,      double& milesPerHour)
 
Old 02-10-2003, 02:49 AM   #6
GtkUser
Member
 
Registered: Sep 2002
Location: Canada
Distribution: Redhat 9.0
Posts: 637

Rep: Reputation: 30
Quote:
Originally posted by PTBmilo

I just thought that if you declare a variable in a block, that all functions called from that block can access them, but I guess that's wrong
You have to pass local varibles as arguments to function calls because they are allocated on different runtime stacks.

Code:
#include<iostream>

int DoubleVar ( int localVar )
{
  localVar *= 2;
  return localVar;
}

int main()
{
  int localVar = 10;

  //pass localVar by value, it needs to be returned to update main's copy
  localVar = DoubleVar( localVar );
  std::cout << localVar << std::endl;
  return 0;
}
The argument is copied because it is passed by value, so you have to return it it in an assignment in order to double the size of the localVar in main. The main runtime stack is separate from DoubleVar's runtime stack.

Code:
#include<iostream>

void DoubleVar ( int * localVar )
{
  (*localVar) *= 2;
}

int main()
{
  int localVar = 10;

  DoubleVar( &localVar );
  std::cout << localVar << std::endl;
  return 0;
}
On the other hand when you pass by reference, you pass a pointer to DobuleVar's runtime stack to the memory location on mains runtime stack. So updates to the value are occuring at memory locations on main's runtime stack.

Actually C++ has a nicer syntax for passing by reference
Code:
#include<iostream>

void DoubleVar ( int & localVar )
{
  localVar *= 2;
}

int main()
{
  int localVar = 10;

  DoubleVar( localVar );
  std::cout << localVar << std::endl;
  return 0;
}
 
Old 02-10-2003, 12:48 PM   #7
leed_25
Member
 
Registered: Jul 2002
Location: san francisco
Distribution: freebsd
Posts: 102

Rep: Reputation: 17
You might want to do a web search on the terms 'lexical scope' and 'dynamic scope' if you would lijke a slightly deeper understanding of this issue. C++ is lexically scoped.
 
Old 02-10-2003, 05:59 PM   #8
PTBmilo
Member
 
Registered: Jan 2003
Posts: 167

Original Poster
Rep: Reputation: 30
Thanks to the both of you..... this is some interesting stuff.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Python inheritance and scope dakensta Programming 2 07-31-2005 07:16 AM
KDE- Out of Resolution Scope vijayind Fedora 2 02-23-2005 07:59 AM
structs & scope jnusa Programming 6 11-16-2004 06:33 AM
Can get into work VPN, but not to my ip scope bclay1 Linux - Networking 0 11-09-2004 10:07 AM
scope suchi_s Programming 1 10-30-2004 08:07 AM


All times are GMT -5. The time now is 09:31 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration