Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty in NULL concept in C?

Tags:

c

NULL in C programming can anyone tell me how NULL is handled in C? And the output of this program is 3, how with NULL concept?

#include <stdio.h>

int main(void) {
    int i;
    static int count;
    for(i = NULL; i <= 5;) {
        count++;
        i += 2;
    }

    printf("%d\n",count);
    return 0;
}
like image 745
Vishwanath Dalvi Avatar asked Sep 12 '10 17:09

Vishwanath Dalvi


People also ask

How NULL is defined in C?

In computer programming, null is both a value and a pointer. Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

IS NULL always false in C?

In any correct C compiler "NULL == 0" is true, even if a null pointer does not really contain 0. What you can't do is memzero a pointer and then assume it will be NULL.

Why NULL is used in C?

Some of the most common use cases for NULL are: a) To initialize a pointer variable when that pointer variable hasn't been assigned any valid memory address yet. b) To check for a null pointer before accessing any pointer variable.

Why is NULL undefined in C?

This happens because NULL is not a built-in constant in the C or C++ languages. In fact, in C++, it's more or less obsolete, instead, just a plain 0 is used.


2 Answers

For C, "NULL" is traditionally defined to be (void *)0 - in other words, it's a pointer alias to address 0. For C++, "NULL" is typically defined to be "0". The problem with NULL in C++ and C is that it's not type safe - you can build bizarre constructs like the one you included in your code sample.

For C++, the language designers fixed this in C++0x by adding a new "nullptr" type which is implicitly convertable to any pointer type but which cannot be converted to an integer type.

like image 109
ReinstateMonica Larry Osterman Avatar answered Oct 13 '22 00:10

ReinstateMonica Larry Osterman


NULL is just a macro defined in stdio.h or a file that stdio includes. It can variously be defined as some variation of zero.

If you run your code through the C pre-processor (usually cc -E) you can see what it translates to on your implemnentation:

void main(){
    int i;
    static int count;
    for(i=((void *)0); i<=5 ;){
       count++;
       i+=2;
    }
    printf("%d",count);
}

which is not only an unnecessary use of NULL but is wildly un-idiomatic C code, more ordinary would be:

int main(){
    int i;
    int count = 0;
    for(i = 0; i <= 5; i += 2){
       count++;
    }
    printf("%d\n",count);
    return 0;
}
like image 42
msw Avatar answered Oct 13 '22 00:10

msw