Question about Null vs zero

I have this function:

void ToUpper(char * S)
{
    while (*S!=0)
    {
       *S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
       S++;
    }
} 

What does this mean for * S! = 0, should it be zero?

+3
source share
5 answers

This checks the end of the string, which is a character that has a value of 0. It has nothing to do with NULL pointers.

+9
source

I would write it *S != '\0'because I feel it is more idiomatic, but it really is just a personal style. You are checking for a null character (ASCII NUL).

You can also consider checking S != 0before any of this code, since the pointer itself may be null and you do not want to dereference the null pointer.

+4
source

NULL - C C++

in C

#define NULL 0

in C++

#define NULL (void*) 0
0

I like algorithms better than loops:

#include <algorithm>
#include <cstring>
#include <cctype>

void ToUpper(char* p)
{
    std::transform(p, p + strlen(p), p, toupper);
}

This solution also works for character encodings where a to z are not sequential.

Just for fun, here is an experiment that performs only one iteration using algorithms:

#include <algorithm>
#include <cassert>
#include <cstring>
#include <cctype>
#include <iostream>
#include <iterator>

struct cstring_iterator : std::iterator<std::random_access_iterator_tag, char>
{
    char* p;

    cstring_iterator(char* p = 0) : p(p) {}

    char& operator*()
    {
        return *p;
    }

    cstring_iterator& operator++()
    {
        ++p;
        return *this;
    }

    bool operator!=(cstring_iterator that) const
    {
        assert(p);
        assert(!that.p);
        return *p != '\0';
    }
};

void ToUpper(char* p)
{
    std::transform(cstring_iterator(p), cstring_iterator(),
                   cstring_iterator(p), toupper);
}

int main()
{
    char test[] = "aloha";
    ToUpper(test);
    std::cout << test << std::endl;
}
-1
source

NULL is a pointer, and * S is the value stored in the pointer. Thanks to Dennis Ritchie, the number 0 is available for both.

-1
source

Source: https://habr.com/ru/post/1738793/


All Articles