|
-
February 4th, 2007, 11:06 AM
#1
simple c++ question
Hi,
I have 2 C++ basic questions:
1. I understood that using this:
for(int i=0; i<5; ++i)
is better than using this:
for(int i=0; i<5; i++)
the first only increments and the second assign and incremement
can someone please give me a deeper explanation regarding this issue?
2. When I use unsigned int and do the following:
unsigned int x = -1;
what will happen?
what I really want to know is this:
If I defined a variable as unsigned int and it is an output parameter and the one using it will put there a negative value by mistake, what will happen
Should I check that the out param is not < 0?
For example
main
{
unsigned int x_array[5];
....
// iterating on x_array
for(int i=0 ; i<5 ; ++i)
{
//do I have to check if x_array[i] < 1
//or can I be sure that the value is positive ?
}
}
Thanks
Avi
-
February 4th, 2007, 07:06 PM
#2
Re: simple c++ question
Hello!
1. The ++x and x++ are two differents things. In ++x before an operation the variable is increment, and on x++ after an operation the variable is increment. In this case it is the same.
2. ALWAYS check if the value is correct, you can have headache if you don`t do it, imagine i put an input for a int "HOls" the program will crash.
ALWAYS check that is is a valid input (Test it with a char[], because the input can be everything, but the program won`t crash), and then put it into the variable.
-
February 4th, 2007, 09:25 PM
#3
Re: simple c++ question
 Originally Posted by avi123
2. When I use unsigned int and do the following:
unsigned int x = -1;
what will happen?
What will happen is:
a. A compiler warning will be issued
b. x will take a value of 0xFFFFFFFF
c. Note that b. is implementation dependent and thus undefined behavior.
-
February 5th, 2007, 04:46 PM
#4
Re: simple c++ question
 Originally Posted by namezero111111
What will happen is:
a. A compiler warning will be issued
b. x will take a value of 0xFFFFFFFF
c. Note that b. is implementation dependent and thus undefined behavior.
No it's not. The computer has no real idea about signed vs. unsigned. "0 - 1" will always be represented by 0xFFFFFFFF. It's the "front end" interpretation that either makes it a "-1" or a "4294967295". Both these numbers are represented by the binary value of 0xffffffff.
Pre-increment is generally prefered to post increment for the case of non-POD. Things like iterators for the STL. Preincrement may run faster, because the compiler will not have to make a temporary copy of the iterator.
Viggy
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|