extern global static?

closed account (iTkG1hU5)
hey I need some help, i want the veriable "seed" to stay declared and defined throughout the whole program, and I want to define it in the funcion setseed,i also want it to be set by default to 1. I know that i have to delare it differently but i do not know how, i hope you can help me, thanks in advance

void setseed(int seed);
printf("%d",int seed);

unsigned int getrand(void){
seed=(9001*seed+29) % 225;
return seed;
}
int main (void){
int i;
int seed;
setseed(1000);
for(i=1;i<=5;i++)
printf("%u ",getrand());
return 0;
}
i want the veriable "seed" to stay declared and defined throughout the whole program, and I want to define it in the funcion setseed
You can't have both.

What you're asking for is a variable that exists in a larger scope. As your program only has functions, you really mean you want a global variable--that's usually not the best thing though; everything has context and thus scope.
closed account (iTkG1hU5)
thanks for you answer, my task strictly says that my using this set of comands
setSeed(1000);
for (i = 1; i <= 5; ++i)
printf("%u ", getRand());
i should get 129 158 187 216 20, i dont know how else to do it?
kbw, static variable declaration in the function...?
Grg> i want the veriable "seed" to stay declared and defined throughout the whole program,
Grg> and I want to define it in the funcion setseed

kbw>> You can't have both.

kbw, +1.

The same variable seed needs to be visible in two different functions: setseed() and getrand().

Either go through some contortions to telescope the functionality of both setseed() and getrand() into one function where seed is defined at block scope with static storage duration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

unsigned int getrand( bool set_seed = false, unsigned int seed_val = 0 ) {

    static unsigned int seed = 1 ;

    return seed = set_seed ? seed_val : (9001*seed+29) % 225;
}

void setseed( unsigned int seed ) { getrand( true, seed ) ; }

int main()
{
    setseed(1000) ;
    for( int i = 0 ; i < 5 ; ++i ) std::cout << getrand() << ' ' ;
}


or define seed with internal linkage at namespace scope.
Would it work to put the functions in a class and set the seed in the constructor? Would that keep the seed in scope for the two functions?


Alternatively, you can use a class with a counter that counts how many numbers have been generated, then in each function reseed with the same seed, then fill the target with rand a number of times equal to the number of previous results plus one (then add one to the counter)
closed account (iTkG1hU5)
thanks everyone, i solved the problem. Aldough we did not do class or iostream header, and i asked in the beginners section. I kinda wonder what have we been doing this whole semestar haha but still im glad to se i have plenty to learn. Thanks again
Topic archived. No new replies allowed.