-3

I'm trying to understand how do rand and srand functions work:

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    unsigned int seed;
    printf("please type in new seed:\n");
    scanf("%i", &seed);
    void srand(unsigned int seed);
    int rand(void);
    printf("%i\n", rand);   
    return 0;
}

But my compiler says:

format %i expects argument of type int, but argument 2 has type int (*)(void) [-Wformat=] printf("%i\n", rand);

Where is the mistake?

Voicu
  • 56
  • 5
Abraham Lincoln
  • 57
  • 2
  • 10

2 Answers2

4

You have some basic syntax misunderstandings. When you write:

void srand(unsigned int seed);
int rand(void);

those are declarations of the functions, it doesn't call the functions. To call a function, you don't include the parameter and return types, you just put the arguments (if needed) inside the ():

srand(seed);

Then you print the result with:

printf("%d\n", rand());

The () after rand means to call the function; the value it returns will be passed to printf(). Since you left this out, your code tried to pass the function pointer itself to printf(), rather than the value it returns.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You got "parameter" and "argument" the wrong way round :-) – Kerrek SB Feb 16 '17 at 20:24
  • @KerrekSB I can never remember which is which. – Barmar Feb 16 '17 at 20:25
  • Think "default argument", that gives you a reliable clue. Or "vaargs -- variable arguments". Or "argument-dependent lookup" if you're playing for the winning team. – Kerrek SB Feb 16 '17 at 20:25
  • @KerrekSB Doesn't help, I can also think "default parameter". – Barmar Feb 16 '17 at 20:28
  • Ironically, your very last sentence makes mockery of itself: You try to pass the function pointer to `printf`, not to `printf()`! The latter is an `int`. – Kerrek SB Feb 16 '17 at 20:28
  • Don't think that! :-) – Kerrek SB Feb 16 '17 at 20:29
  • @KerrekSB See also http://stackoverflow.com/a/156859/1491895 – Barmar Feb 16 '17 at 20:30
  • 3
    Yes, but that doesn't help you (or lesser beings) get a clear head about programming. It's best to think that "parameters are part of the function", and "arguments are part of the call". – Kerrek SB Feb 16 '17 at 20:31
  • @KerrekSB My writing style is to put `()` after a name to indicate that it names a function. – Barmar Feb 16 '17 at 20:31
  • 1
    @Barmar: That's ungood. Think about `typedef void F(int);` and `F * f(...);`. It's a big difference whether you pass `5` to `f` or to `f()`! – Kerrek SB Feb 16 '17 at 20:41
  • @KerrekSB When higher-order functions aree involved, I'll use more descriptive language like "The function returned by f()`. – Barmar Feb 16 '17 at 21:22
-2

You pass function instead of an integer... try:

printf("%i\n", rand()); 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Kupto
  • 2,802
  • 2
  • 13
  • 16