why the hell won't this work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool isInString( char c, const char* str )
{
    while( str != nullptr ) {
        if( *str++ == c ) return true;
        std::cout << "*str : " << *str << '\n'; // test
    }
    return false;
}

int main()
{
    const char* str = "ABCDEFHIJKLMNOPQRSTUVWXYZ";
    
    if( isInString( '2', str ) ) { // well, this condition executes
        std::cout << "Found '2' in " << str << '\n';
    }
}


Output :
*str : B
*str : C
*str : D
// ... blah
*str : Y
*str : Z // something's wrong below
*str : 
*str : F
*str : o
*str : u
*str : n
*str : d
*str :  
*str : '
*str : 2
Found '2' in ABCDEFHIJKLMNOPQRSTUVWXYZ
Because str will never be a null pointer (it would be if program would not encounter uninitialized memory and crash before str could overflow)

After you cheched whole string your program moves further in random memory. In your case it is where all string constant are stored (as you can see from output)

You possibly wanted to check if you encountered null symbol (end of string). in that case you should use while(*str != '\0') or just while(*str)
Last edited on
Oh, i see, thank you very much !!
Topic archived. No new replies allowed.