-
Too confuse
Hey people,
I am a newbie to C++. I have learn from the books
that C++ has strong type checking, but when I tried out a small program below and compiled with
MS-Visual C++ 6.0, it raise no warning or error?
Can anyone explain why? Thanx
#include <iostream.h>
int main()
{
int a;
char b;
cout<<"size of a: "<<sizeof(a)<<endl;
cout<<"size of b: "<<sizeof(b)<<endl;
a = 10;
b = 105; //why OK with integer 105 instead of a
//character as b = 'H', no compiler //warning here???
cout<<a<<" and "<<b;
cout<<a + b; //Confuse??? why int + char is //OK, no error???no warning??
return 0;
}
-
char is really just a small integer (short int is bigger, and long int is bigger than short int). This is part of the historical link with C.
So all that happens when you have
char_var + int_var
is promotion of the char_var to an int_var, and then the addition takes place as you would normally expect for integer arithmetic.
When you say
char b = 'A';
this is a normal assignment of one char value to another char value
Doing
char b = 65;
is an int to char assignment, which involves some truncation - which the compiler will normally do silently if it sees the value will fit in a char anyway.
-
When the promotion takes place is a temporary variable created?
-
-
Do you know fountain? I could do with some help on this matter.
-
in most cases i do not think so. c compilers nowadays do many optimizations. here's an easy way to think of it.
in every x86 computer, there are 4 general-purpose registers: eax, ebx, ecx, and edx. they hold 32-bit integers. 'al' in assembly stands for the least significant 8 bits of eax. 'ax' is the least significant 16 bits of eax.
assembly code:
Code:
mov eax,0 ;eax = 0
mov al,[memory_location] ;al = *(memory_location)
your compiler would normally pull a char variable out of memory and store it in al. al can then be promoted to eax with no trouble at all. eax is used instead of al by the assembler. sometimes your compiler will even optimize further, circumventing the whole promotion deal.
in short: most of the time, no. however, if you're working with many chars and it's impossible to conviently use the bigger register, your compiler might need a temporary variable. but it's far more likely that your compiler has already prepared the code so that it is convienent to promote the char.
however, if you're using floating point variables, that promotion has likely already taken place. all floating point variables are stored in their registers in 80-bit mode, bigger than any normal float or double. a simple change in commands would be needed.
-
Thanks for the explanation, it's a lot clearer now.