Why can't I initialize my guessing game's number outside main in C?

November 16, 2026 5 answers
Asked by c.748+plumwrench

I made a simple number guessing game as my first C program. I originally put int num = rand() % 100 + 1 outside main, but was told to move it inside. Why does that matter? Other suggestions are welcome too.

Answers

Vexaro+2m

At file scope, num has static storage duration, and C restricts its initializer to a constant expression. A call to rand() isn't one, so that declaration isn't valid standard C.

Inside main, an ordinary local variable is initialized when execution reaches its declaration. That means int num = rand() % 100 + 1 can call rand() and use the result. Think of the file-scope rule as a language restriction, not a sign that your game logic is wrong.

_v54~hingequarry.8:

Does that mean nothing happens before main starts?

Reply to this answer
8f~circuitlantern_462

Keeping num local is also a nice habit. The game only needs it in main, so there isn't much reason to make it available elsewhere. In a tiny one-function program that distinction won't change much, but it helps keep larger programs easier to follow.

Reply to this answer
_h91~ticketmixer.6

Check the return value from scanf before comparing x. If the input isn't an integer, scanf returns without assigning a value to x. You could end up comparing an uninitialized or stale value, and the invalid input can keep causing the same failure on the next pass.

For a simple version, print an error and exit when scanf doesn't return 1. If you want to let the player retry, you'll also need to discard the invalid input first.

Reply to this answer
5q+orbitthimble_731

One more thing about rand(). Without seeding it, a program will typically produce the same sequence each time it runs. You can call srand once before rand if you want different games, though this isn't a source of secure randomness.

Also, rand() % 100 + 1 gives a value from 1 through 100, but the results may not be perfectly uniform. That's usually fine for a small guessing game.

Reply to this answer
r.582~corkpiston

Your loop structure is fine for this. A do while loop is another option since the player needs at least one guess, but the existing infinite loop with a break on success is easy enough to read.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions