use of if else



the code run,there is no error but the output is else condition whenever input character are entered same
how can I modify, Want to know appropriate use of if else statemennt.


#include <iostream>

using namespace std;
char name1[5];
char name2[5];
char favclr1[5];
char favclr2[5];
int main()
{
cout << "enter your name \n";
cin >> name1;

cout << "enter the name of your mate \n";
cin >> name2;

cout << "enter your favourite colour \n";
cin >> favclr1;
cout << "enter your friend's favourite colour \n";
cin >> favclr2;

if ( char favclr1 = favclr2[5])
{

cout<< " your taste match" << endl;
}
else
{
cout << "your taste doesn't match " << endl;
}
return 0;
}
Look at the code below:

if ( char favclr1 = favclr2[5])

There are at least two problems with this code.

One do you know the difference between the operator= and the operator==?

Two your array is defined with a size of 5, so trying to access element 5 produces undefined behavior. Arrays in C++ start at zero and stop at size - 1.

Is there any other things that can perform the task of if else accessing more then 1 value?
Yes, there are many different ways depending on the type of variables in question.

By the way how many problems did you discover and fix about the snippet I showed in my last post?

How did you fix the problems you discovered?

Another problem in the original post:

The variable favclr1 is being redefined. In the global namespace it was an array of char. Now a new favclr1 is being defined with type char. It's legal, but I don't think it's what was intended.
You need to fully understand what was said above, but basic conditionals work like this:

if its just one or two, you can tie them together with logical operations.
&& is and, || is or in c++. ! is not.
so

if(fav[3] == 11 && fav[1] != 42) //two conditions in one if

or if you want to check all in an array
for(int x =0; x < arraysize; x++)
if(fav[x] <= 13)
...;

and finally multiple conditions on the same thing
if(fav[2] !=11 && fav[2] !=36) //explicit, state each condition fully, there is no shortcut.

a source of trouble for beginners is the double operators.
&, | are very different from && and || but both will compile and 'work' they just won't do what you want every time. same for = and ==, etc. Be very careful with these.
Last edited on
Topic archived. No new replies allowed.