-1

I know that runtime error occurs when program consumes large memory or divide by 0 somewhere. this is the code which prints all the numbers until user types 42.(does not print 42).

#include<stdio.h>
int main()
{
    int n;
    while(1)
    {

        scanf("%d",&n);
        if(n==42)
            break;
        else
            printf("%d",n);

    }
} 

please tell me why am I getting runtime error in such a simple code?

explorer
  • 27
  • 1
  • 8

2 Answers2

1

Your main function should return a int and you're not: that's why you get a Runtime Error. Here is the correct code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 0;
    while(1) {

        scanf("%d",&n);
        if(n == 42)
            break;
        else
            printf("%d",n);

    }
    return EXIT_SUCCESS;
}

You can also change return EXIT_SUCCESS; in return 0; if you don't want to include stdlib.h but here is why it's better.

You should also consider using another IDE than CodeChef. CodeBlocks or VisualStudio are better and more explicit with errors and warnings. And you should set you int n to 0 before using it.

Community
  • 1
  • 1
Sisyphe
  • 146
  • 1
  • 13
  • So,adding return 0 worked...but **what is the relation of this with runtime error?**the concept of runtime error is like :if you are consuming too much memory from stack then runtime error occurs,right? – explorer May 20 '17 at 11:04
  • Runtime error doesn't mean that you're using too much memory. It just says an error occurred at runtime because the compiler didn't see the error during compilation. It can be a memory issue, but not always. – Sisyphe May 20 '17 at 11:13
  • When a program encounters an error it'll exit with a non-zero code. That's why codechef thinks there's some problem with your program – phuclv May 20 '17 at 12:35
  • "*And you should set you `int n` to 0 before using it.*" Why? An explanation would be great. – alk May 20 '17 at 15:05
1

This works perfectly fine as it is except when running on CodeChef.

According to the C standard (at least C99 and C11) a return 0 is implicit when main() ends without returning something. So even though it can be argued that it is a good idea to always have a return 0 at the end of main(), it is not wrong to skip it.

But that's not the case when running on CodeChef. For some reason they tread it as a run time error if main does not end with return 0.

SiggiSv
  • 1,219
  • 1
  • 10
  • 20