# Thread: Explain this IF statement, please.

1. ## Explain this IF statement, please.

Please take a look at this code:
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Tells computer when ARRAY_SIZE is used to automate 100
#define ARRAY_SIZE 30

int main(void){

char continueResponse; //Y/N
int count = 0;
int i; //loop conditional variable

//allocates memory for the data
grade =malloc(sizeof(int) * ARRAY_SIZE);
exit(1); //return 1;
}

printf("This program will create a list of your grades.\nPress ENTER after each grade.\n\n");

//input loop
for(i = 0; i < ARRAY_SIZE; i++)
{
printf("Enter grade percentage(0-100) [%02d/%02d]: ", i+1, ARRAY_SIZE);
scanf("%d",&grade[i]); //caps the inputs to array size of 30
count++; //count=count + 1; increments to next position in array
printf("Continue? (Y/N): ");

if(continueResponse != 'Y' &&continueResponse != 'y')
{
printf("\n == Grade Book ==\n\n");
break;//break out of for loop
}
}

for(i = 0; i < count; i++){
}

return 0;
}```
What is this section doing? How/why is the "1" variable there?

Code:
```if(grade == 0){
exit(1); //return 1;```

2. 1. malloc returns NULL when it fails to allocate the requested memory.

2. A simple 0 is silently cast to NULL when used in a pointer context, such that if ( grade == 0 ) becomes if ( grade == NULL )

3. The traditional return / exit from main is 0 for success or 1 for error.
For the most part, exit(n) and return n; in main are the same thing.

Most programs don't exist in isolation, so it's useful to be able to communicate success/failure to the environment.

In a Linux/Bash environment, you could do this.
Code:
```myprog.exe
if [ \$? == 0 ]; then
echo "Your program was successful"
else
echo "Your program failed!"
fi```
Where \$? contains the value that your main exited with.

3. Originally Posted by Salem
3. The traditional return / exit from main is 0 for success or 1 for error.
For the most part, exit(n) and return n; in main are the same thing.
.
You should exit(EXIT_FAILURE); rather than with a constant to be portable. However most OSes don't have a strong concept of a process "failing". It can be hard to define for many real programs.

Popular pages Recent additions