It's supposed to be function that returns two random numbers depending on a range chosen by the user, I read I could use pointers to return two values from a function but I get the error expected an identifier right before int* ran1 and int* ran2and when I run the code I get the error expected ')' before 'int' Both ran1 and ran2 are global variables. Even when I use different names for the pointers I still get the same error.
int level(lev, ran1, ran2, int* ran1, int* ran2){
srand(time(0));
if(lev == 'l'){
ran1=(rand()%10 1);
ran2=(rand()%10 1);
}
if(lev == 'm'){
ran1=(rand()%50 11);
ran2=(rand()%50 11);
}
if(lev == 'h'){
ran1=(rand()%100 51);
ran2=(rand()%100 51);
}
}
CodePudding user response:
"I get the error expected an identifier right before int* ran1 and int* ran2"
The C compiler error message phrase "expected an identifier" is seen for many syntactical errors, across a wide variety of compilers (even for other languages) In this case it is simply pointing out the compiler does not recognize lev as a defined type, and because an identifier cannot be defined without using a type, you get this squawk.
int level(lev, ran1, ran2, int* ran1, int* ran2){
lev, from the context of its usage in your code example could either be defined as char, or int, where ran & ran2 are likely best typed as int
int level(char lev, int ran1, int ran2, int* ran1, int* ran2){
But as the code below shows, not all of these parameters are necessary to accomplish what your code example is doing.
Note, when passing a int pointer to be updated, its value needs to be updated, which in this case will be *ran1 or *ran2, not ran1 or ran2.
(the * symbol when used in this context de-references a pointer, and in this example, the de-referenced pointer is the value to be updated.)
Also, as pointed out in comments, srand() needs only to be called once during a program session, and should be seeded such that if the program has a short run-time duration, and may be called in quick succession, will have a unique seed value for each call.
The following illustrates these corrections in your code:
int level(int lev, int *ran1, int *ran2){//removed unused parameters
//srand(clock());//moved to main, so just called once
if(lev == 'l'){
*ran1=(rand()%10 1);//Updating value *ran1 not pointer ran1 (apply to all)
*ran2=(rand()%10 1);
}
if(lev == 'm'){
*ran1=(rand()%50 11);
*ran2=(rand()%50 11);
}
if(lev == 'h'){
*ran1=(rand()%100 51);
*ran2=(rand()%100 51);
}
return 0;//prototype requires a return statement
//alternatively, the prototype can be made void
//as 'level(...)' returns its work via its parameters.
}
int main(void)
{
//calling this only once per execution,
srand(GetTickCount());//number of milliseconds elapsed since system started,
int lev = 1, ran1, ran2;
level(lev, &ran1, &ran2);
return 0;//int main(void) requires a return statement
}
