Simple cout question

Below program gives output "me here". That mean's it's eliminating the initial 5 characters from the string because of "5 + " before it. An explanation of its working will be appreciated. Thank you.

1
2
3
4
5
6
int main()
{
	cout << 5 + "welcome here" << endl;

	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//"Welcome here" is a "pointer to character" (I think)
char* s; //<<Pointer to character

//So  probably, when you write: 5 + pointer
//the pointer increases. So instead pointing to a first character
//it points to the fifth, skipping the first two.

//Also, pointers and vectors are connected
//(I better understand vectors rather than pointers. btw)
char* s; = char s[];


//So if we apply the same logic here, the string would look like str[n+5]
//Just skipping first 5 chars.

//edit: why have I wrote all in comments ? 
Last edited on
Yes, string literals are const char * and so you can change which char they point to but you can't change the data they are pointing to. Because you can add in any order (1+2 == 2+1), that is the same as doing this:
1
2
3
const char *text = "welcome here";
text += 5;
cout << text;


ihato, I think you mean 'arrays' and not 'vectors'. There is a very significant difference between a pointer and an array, and the syntax makes it hard to tell:
1
2
3
4
5
int *p; //pointer to int
int[] ia; //pointer to int
int ai[]; //pointer to int
int[5] arr; //array of five ints
int arr2[7]; //array of seven ints 
Don't believe me? Try couting the sizeof the variables above. Arrays are also implicitly pointers, but the data they point to are allocated on the stack automatically.
Last edited on
I got it. Thank you ihato and L B. :)
Topic archived. No new replies allowed.