-3

I didn't know that declaring value on namespace is same as declaring value on global.

So I want to change my code which don't use global variable.

How can I keep track of Fibonacci number from 0 ~ 20 without using global variable?

#include <iostream>
using namespace std;
int Fibonacci(int num);
namespace Fib{
    int arr[100];
    int num;
}
int main(){
    cin >> Fib::num;
    Fibonacci(Fib::num);
    return 0;
}

int Fibonacci(int n){
    if(Fib::num < 1) return -1;
    int result = 0;
    int idx;
    result = (n == 0) ? 0 : (n == 1) ? 1 : Fibonacci(n-1) + Fibonacci(n-2);
    Fib::arr[n] = result;
    if(n == Fib::num){
        for(idx=1; idx < n+1 ; idx++){
            cout << Fib::arr[idx] << " ";
        }
        cout << endl;
    }
    return result;
}
nujabes
  • 891
  • 2
  • 8
  • 17

1 Answers1

1

The problem with this code is not with usage of namespaces. It is with usage of global variables. There are unlimited reasons to not use global variables, and may be one or two scenarios where it is appropriate. It is not appropriate here.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Does using namespace means using global variables? – nujabes Sep 13 '16 at 17:52
  • @nujabes, only if you put variables inside your namespace :) – SergeyA Sep 13 '16 at 17:53
  • Oh, then namespace obj1 { int a = 5 } – nujabes Sep 13 '16 at 17:54
  • and namespace obj2 { int b = 5; } These statement uses global variables then? – nujabes Sep 13 '16 at 17:54
  • You mean that I can't use namespace as 'object in Javascript'? – nujabes Sep 13 '16 at 17:55
  • @nujabes, yes, your examples use global variables. It is usually not appropriate. Namespaces are not objects, by the way. Objects are, ... well, objects. – SergeyA Sep 13 '16 at 17:56
  • Then, how can I make a 'packages' which doesn't use global variables? – nujabes Sep 13 '16 at 17:56
  • Thank you for kind answer :) – nujabes Sep 13 '16 at 17:56
  • @nujabes, it is not clear what you are trying to achieve, and what do you need those 'packages' for. – SergeyA Sep 13 '16 at 17:57
  • #include using namespace std; int Fibonacci(int num); namespace Fib{ int arr[100]; int num; } int main(){ cin >> Fib::num; Fibonacci(Fib::num); return 0; } int Fibonacci(int n){ if(Fib::num < 1) return -1; int result = 0; int idx; result = (n == 0) ? 0 : (n == 1) ? 1 : Fibonacci(n-1) + Fibonacci(n-2); Fib::arr[n] = result; if(n == Fib::num){ for(idx=1; idx < n+1 ; idx++){ cout << Fib::arr[idx] << " "; } cout << endl; } return result; } – nujabes Sep 13 '16 at 18:06
  • I want to push Fibonacci[0] ~ Fibonacci[20] value to the array, and I want to print of it. I thought that then I must use outer 'packages'. – nujabes Sep 13 '16 at 18:07
  • @nujabes, edit the question with relevant code, or, since this question is in kinda bad shape, better create a new one. – SergeyA Sep 13 '16 at 18:18
  • Thank you Sergey! – nujabes Sep 13 '16 at 18:18