-
srand and rand
So I'm getting 2 compiler errors:
Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int; line 20
Error 2 error C2365: 'srand' : redefinition; previous definition was 'function'; line 20
I'm trying to incorporate rand into my blackjack deck for later purposes, with the seed set as time for randomizing purposes. But I get those 2 compiler errors, and I'm uncertain what's wrong with what I have:
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
void printBinary(char x);
void printCard(char x);
char cards[52];
enum suits {
spade = 0x30,
diamond = 0x20,
heart = 0x10,
club = 0x0
};
srand( time(NULL) );
int main() {
int x = 0;
int c = 1;
int t = 0;
for (int i = 0; i < 52; i++) {
if (c > 13) {
c = 1;
t+=16;
}
cards[i] = c | t;
c++;
}
while (x < 52) {
printCard(cards[x]);
cout << endl;
x++;
}
}
void printBinary(char x) {
int c = 0;
for (int i = 0x80; c < 8; i>>=1) {
c++;
if (i & x)
cout << "1";
else
cout << "0";
}
}
void printCard(char x) {
char card = 0xF & x;
if (card == 13)
cout << "K";
else if (card == 12)
cout << "Q";
else if (card == 11)
cout << "J";
else if (card == 1)
cout << "A";
else
cout << (int)card;
char suit = 0x30 & x;
if (suit == spade)
cout << "S";
else if (suit == club)
cout << "C";
else if (suit == heart)
cout << "H";
else if (suit == diamond)
cout << "D";
}
Cheers.
-
Put the call to srand() at the start of the main() function body instead.
-
Yeah that worked haha thank you, mind explaining why? :D
-
You can't have function calls outside of other functions (unless you are declaring a global variable and calling a function to initialize it):
Code:
int foo() { return 42; }
foo(); //can't do that
int global42 = foo(); //Ok
int main() {}
-
The code is still non-compliant, though. <cstdlib> and <ctime> define their functions in the std namespace, and not outside, but you call them as though they were outside.
This happens to work because many compilers (sometimes depending on settings) declare those functions outside the namespace, too.