-2

I am a beginner in C programming.

I have written a program which is not functioning due to its 'OR' functionality. Here is a working code snippet:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* englishTest = 'yup';

    if ( (englishTest == 'yup') || (englishTest == 'yep') || (englishTest == 'yas') || (englishTest == 'yah') )
    {
        printf("You may pass \n");
    }
    else
    {
        printf("You shall not pass \n");
    }
    return 0;
}
Rushat Rai
  • 743
  • 2
  • 15
  • 31

1 Answers1

2

This is supposed to be C, not a scripting language.

There are two problems in this code:

char englishTest = 'yup';

englishTest is declared as char which in C is an integer type. It can hold only one character but you attempt to store three characters in it.

What you probably meant is:

char englishTest[] = "yup";

Please note the square brackets that denote an array (of chars). The array size can be optionally specified between the brackets. It is not specified here and the compiler uses the smallest value that can hold the string used for initialization ("yup"). This smallest value is 4: there are 3 characters in "yup" but C strings are terminated with the NULL character ('\0').

The second issue in your code is the comparison of strings. The strings are not primitive types in C. They are arrays of characters. Directly comparing two strings using the comparison operators doesn't produce the result you expect. It compares the addresses in memory where the two strings are stored, not their characters.

The C standard library provides several functions to compare two strings. The most straightforward string comparison function is strcmp(). It returns 0 if the two strings are identical, a negative value if the first string comes before the second string in the dictionary order or a negative value otherwise.

Your comparison code should be (note the C strings are enclosed in double quotes ""):

if (strcmp(englishTest, "yup") == 0 || strcmp(englishTest, "yep") == 0 ||
    strcmp(englishTest, "yas") == 0 || strcmp(englishTest, "yah") == 0)


P.S. The OR operators (||) do not break anything here.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Hi, thanks for your answer :) When I tried- char englishTest[ ] = 'yup' then codeblocks told me "error: invalid initializer". When I tried- char* englishTest = 'yup' it worked. What could be the reason for this? – Rushat Rai Dec 27 '16 at 09:54
  • @MythicCocoa the compiler will have issued you warnings for `'yup'` - please take note of them. – Weather Vane Dec 27 '16 at 09:55
  • @WeatherVane in fact, it did. I didn't think much of these warnings if the code worked. I've learned my lesson :) – Rushat Rai Dec 27 '16 at 09:58
  • 2
    @MythicCocoa "it works" is no proof, perhaps lucky, That luck can run out at the very moment you demo the project to a client. – Weather Vane Dec 27 '16 at 10:00