0

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 ?

3
Contributors
6
Replies
9
Views
6 Years
Discussion Span
Last Post by Narue
0

>>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.

Edited by Ancient Dragon: n/a

0

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.

0

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 ??

0

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

0

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.

This topic has been dead for over six months. 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.