The meaning of int

When doing the following code I had accidentally used int instead of char and when running the code it still worked but if I type i or y nothing would happen and the program would just end. Of course if I change the int to char then it works as intended doing the output if I enter the correct characters in console.

So what is the meaning of int, when used before "main()" it seems to work as an initializer for main and executes everything below it but when using it as a variable it seems to be more picky. I hope my question makes sense, lol.

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

using namespace std;

int main()
{
  		int y;
		cin >> y;
		if ((y == 'i')||(y=='I'))
		{
		cout << "Stop" <<'\n';
		}
        else if((y == 'y')||(y=='Y'))
        {
         cout << "Go" << '\n';

        }
    return 0;
}
closed account (j1CpDjzh)
int before a function ("main" for example) mean that a number will be returned from the function. You can learn a bit more about this here: http://www.cplusplus.com/doc/tutorial/functions/

You declare y as a integer, and then test it against 'i' or 'I' - what will happen here is it will check y with the character code of i and I which is 105 and 73.

y should be a char indicating that it is to hold a character.
Last edited on
I think that I understand it now.

Hmm, ya, that's interesting, if I type 105 it does the same as typing i would.
Last edited on
closed account (j1CpDjzh)
That's because you need to define it as a long int I believe.
An int is a signed integral type which typically uses 8 bytes. A char is a signed integral type which typically uses 1 byte. They are both integers.

The difference is that a char is interpreted as a character. Therefore, when you "cin" a char, it is expecting a value from the ascii table, and when you "cin" an integer, it is expecting at least one number
http://www.asciitable.com/index/asciifull.gif

The interpretation also has to do with the output:
1
2
3
4
int i = 105;
cout << (char)i << '\n';  // prints 'i'
char ch = 'i';
cout << (int)ch << '\n';  // prints 105 


Last edited on
And the only int in "int main" is that main() returns an integer value to the operating system.Return 0 if everything went well, 1 if the program has to quit for some error.
tiny screaming yak wrote:
That's because you need to define it as a long int I believe.
?????????????

Also, int like everyone else said is an integer (-2, -1, 0, 1, 2, ...)
For more information on data types please refer to: http://www.cplusplus.com/doc/tutorial/variables/
closed account (j1CpDjzh)
Oh sorry, I got a bit confused.

Whenever I had integer trouble (with more than a few digits), I was able to define it as a long int and it would print out fine? My understanding of that stuff is a bit rusty though and I really should look into restudying it.
Topic archived. No new replies allowed.