output help

i didn't understand why the output of this code is 1? can someone explain to me please? Is it because B is bigger than A; if yes why? thank you!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream.h>

int funcY(const char *, const char *);

int main()
{
	char	string1[40] = "LineB",
			string2[40] = "LineA";
	
	cout << funcY(string1, string2) << endl << endl;
	
	return 0;
}

int funcY(const char *s1, const char *s2)
{
	for ( ; *s1!='\0' && *s2!='\0'; s1++,s2++){
		 if (*s1 > *s2)
			 return 1;
		 if (*s1 < *s2)
			 return -1;
	}
	
	return 0;
}
a) i would just use iostream not iostream.h
b) i think (i could be wrong) that it is converted to its ascii value on lines 18 and 20 and 'B' > 'A'
c) why not else if? or even else?
hello little bobby tables thanks for answering!
anyway i didn't write the code... the teacher gave it to us to practice...
no problem. although just for the record i think you shouldnt be comparing against \0, rather the strings themselves
LBT wrote:
no problem. although just for the record i think you shouldnt be comparing against \0, rather the strings themselves

C strings (char arrays used for text) are NUL-terminated.
This means their last character is NUL (which is '\0').
So the for() loop continues checking characters in s1 and s2 until the first NUL is found.

chry44 wrote:
i didn't understand why the output of this code is 1? can someone explain to me please? Is it because B is bigger than A; if yes why? thank you!!


char's are "seen" as numbers according to the ASCII table.

As ASCII codes, 'A' has the value 0x41 and 'B' has the value 0x42, so 'B' is greater than 'A'.

Note that 0x41 and 0x42 are in base 16 (hexadecimal).
In base 10 (decimal) they would be 0x41 = 65, 0x42 = 66.

http://www.cplusplus.com/doc/ascii/
Last edited on
catfish666 thank you so much!
one more question when return 1 is done it will exit the for loop right?
one more question when return 1 is done it will exit the for loop right?

Yes. A return statement will "exit" the entire function.

In other words, if a return statement is reached, the function ends.
The example below also shows that void functions can have return statements too, but they must be empty returns (obviously).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void func()
{
    std::cout << "This code is reached.\n";
    return;
    std::cout << "This code is not reached.\n";
}

int main()
{
    std::cout << "Before calling func().\n";
    func();
    std::cout << "After calling func().\n";
}
Before calling func().
This code is reached.
After calling func().

thank you again :)
Topic archived. No new replies allowed.