i have a doubt.

why cannot we use clrscr() before initializing a variable in C?
i mean, why wont this work ?

void main()
{
clrscr();

int a,b;

----
----

getch();
}

It'll give an error saying , "Declaration is not allowed here "
Logically speaking , you should be able to put a clrscr() anywhere right ?

Recommended Answers

All 6 Replies

>>Logically speaking , you should be able to put a clrscr() anywhere right ?
Wrong.

1. Its int main, not void main()

2. In C programs all variables must be the first things declared in a block of code. A block of code is one surrounded by { and }

3. clrscr() is a non-standard function found mostly in old ancient borland compilers such as turbo c. If that's the compiler you are using then you probably need to include the appropriate header file that contains its function prototype. It might be in dos.h, but I don't know.

Logically speaking , you should be able to put a clrscr() anywhere right ?

Like here?

void foo(void)
{
    /* ... */
}

clrscr();

int main(void)
{
    /* ... */
}

Or what about here?

struct foo {
    int x;
    clrscr();
    int y;
};

What's your logical interpretation of when those calls should run? Because I can think of several, and none of them are logical. ;) So let's look at your real question.

why cannot we use clrscr() before initializing a variable in C?

Prior to C99, declarations must be the first thing in a block. C99 lifts this restriction and allows declarations to be mixed with executable statements. As for why declarations were limited to the beginning of a block, I'm not entirely sure. Though it would certainly simplify the job of a compiler writer.

Ancient Dragon : Thank you so much for the reply sir.
The explanation was clear.

I tried compiling the same program using a .cpp extension and as expected (based on ur exp), it worked.. :)

But 1 more doubt,
Why did u say, Its int main and not void main ??

Narue : Sorry sir, i had loosely put it as , "anywhere ", my bad.
I meant to say, anywhere within a block of code..

>>Narue : Sorry sir

Narue is a woman (with children) :)

>>Why did u say, Its int main and not void main ??
Read this link

Why did u say, Its int main and not void main ??

int main works everywhere, void main only works for freestanding environments or if the compiler supports it as an extension on hosted environments. Sane programmers much prefer "works everywhere" to "only works if..." when given the choice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.