vendredi 29 avril 2016

weird behaviour when passing function as an argument in C++

I encountered this strange thing with with C++ when i tried to pass a function as an argument to another one. the problem here is that it works but not giving me the expected result. here's my code (msvc2013):

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream>

typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
using namespace std;

#include "stdafx.h"

uint32_t random_color()
{
    uint8_t r = rand() % 255;
    uint8_t g = rand() % 255;
    uint8_t b = rand() % 255;
    uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);

    return rgb;
}

void print_rgb(uint32_t(*color_generator)() = &random_color)
{
    std::cout << color_generator << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < 5; i++)
    {
        srand(time(NULL));
        print_rgb();
    }
    system("PAUSE");
    return 0;
}

the purpose of this code is more complicated, but this is a minimal example.

Question : although as you see, there was an srand(time(NULL)); in order for rand() to change values, it dosen't !

so , at the 5 times, I got the same value ! output

Is there any reason for this ? Am I missing something ?




Aucun commentaire:

Enregistrer un commentaire