0

Hi,
In the following program i have not defined <stdlib.h> header and included rand() function and it works without this header. How?

 #include <stdio.h>
#include <stdbool.h>
#include <time.h>

#define NUM_SUITS 4
#define NUM_RANKS 13
int main(void) {
    bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
    int num_cards, rank, suit;
    const char rank_code[] = {'2', '3', '4', '5', '6', '7', '8', '9', 't', 'j', 'q', 'k', 'a'};
    const char suit_code[] = {'c', 'd', 'h', 's'};
    srand((unsigned) time(NULL));
    printf("Enter number of cards in hand: ");
    scanf("%d", &num_cards);
    printf("Your hand: ");
    while(num_cards > 0) {
        suit = rand() % NUM_SUITS;
        rank = rand() % NUM_RANKS;
        if(!in_hand[suit][rank]) {
            in_hand[suit][rank] = true;
            num_cards--;
            printf(" %c%c", rank_code[rank], suit_code[suit]);
        }
    }
    printf("\n");
    return 0;
}

* The following question is an exercise from K.N. King book*

Edited by ashish2expert: some minor problem in code

3
Contributors
2
Replies
14
Views
4 Years
Discussion Span
Last Post by vegaseat
0

i have not defined <stdlib.h> header and included rand() function and it works without this header. How?

If you don't declare a function before using it, the compiler will assume that it's an external function accepting an unknown number of arguments and returning int. If those assumptions hold true, you're good. It's a horrible practice, but it'll work (barring functions with variable arguments like printf()).

1

C header files often include other header files, which include other header files in turn. By chance you might end up with <stdlib.h> included. I would not rely on it!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.