Regarding this line:
if (firstName[20] == 'Vojta'){
firstName
is an array and its value was set via the scanf()
. Therefore, first name will contain a terminating NULL char ('\0'
).
Therefore, the contents of firstName
, if the user entered 'Vojta'
would be 'V'
, 'o'
, 'j'
, 't'
, 'a'
, '\0'
followed by 14 garbage characters.
Because of the trailing '\0'
(which was inserted by the scanf()
) the contents of firstName
is a valid string.
The best way to compare the contents of firstName
with some string literal, is to compare it to a string literal, using the function strcmp()
.
Note: the current code is comparing the (offset) 20 position in firstName
(which is outside the bounds of the array and therefore results in undefined behaviour).
Here is an example of the right way to make a string comparison:
if( 0 == strcmp( firstName, "Vojta" ) )
Do notice the double quote marks ("
) around the string literal.
Those double quote marks make it a string literal rather than just a bunch of characters that the compiler will evaluate to an 'int' value.
Note: individual characters can be represented by using single quote marks around each character as in: 'V'
, 'o'
, 'j'
, 't'
, 'a'
.
The strcmp()
function
- returns
< 0
if the first parameter (contents of firstName
) comes before (alphabetically) the second parameter.
- returns
> 0
if the first parameter (contents of firstName
) comes after (alphabetically) the second parameter.
- returns
0
if the first parameter matches the second parameter.