C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

A few basic c++ questions

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
Raju
Guest





PostPosted: Sat Apr 16, 2005 12:09 am    Post subject: A few basic c++ questions Reply with quote



I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

1.
------------------------------------------------------

include <iostream.h>
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning messages
mean? Is the 'char *' in the warning indicative of a pointer operation?

P.S

I know that the correct way to setup and intialize the character array
is either:

char characters2[11] =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'n') ;

or
char characters2[11] = "abcdefghij" ;


2.
------------------------------------------------------

#include
int main ()
{

unsigned int IntDisplay = 200 ;
unsigned long LongDisplay = 4294967295UL ;

printf ("Displaying value of IntDisplay using [%%*.*d]: %*.*dn", 3,
10, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%0*d]: %0*dn", 10,
IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f]nWithout
casting IntDisplay to float type: %*.*fn",
10, 3, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f] nafter
casting IntDisplay to float type: %*.*fn",
10, 3, (float) IntDisplay) ;
printf ("Displaying value of LongDisplay using [%%*.*u]: %*.*un", 3,
10, LongDisplay) ;
return 0 ;

}

/*
Output:

Displaying value of IntDisplay using [%*.*d]: 0000000200
Displaying value of IntDisplay using [%0*d]: 0000000200

Displaying value of IntDisplay using [%*.*f]
Without casting IntDisplay to float type: nan

Displaying value of IntDisplay using [%*.*f]
after casting IntDisplay to float type: 200.000

Displaying value of LongDisplay using [%*.*u]: 4294967295

Question:

Please explain the difference between nan and 200.000. why is nan
printed?
*/

3.
------------------------------------------------------

#include <iostream.h>

char mybuffer [100] ;
char yourbuffer [100] ;

int main ()
{

cout << "Please enter a string: " ;
cin.getline(mybuffer, 10, 'n') ;
cout << "The value you entered is : " << mybuffer << "n" ;
strcpy(yourbuffer, mybuffer) ;
cout << "I copied the value you entered into a [yourbuffer] array :
" << yourbuffer << "n" ;
}

/*

Question:

How am I able to use the function strcpy without including the
library file string.h

*/

4.
------------------------------------------------------


#include #include <stdio.h>

int main (void)
{
//unsigned long option = 4294967295 ;
//unsigned long option = (unsigned long)4294967295 ;
unsigned long option = 4294967295UL ;

while (option != 0)
{
printf("The value of option is : %lun", option) ;
//cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
//option = 0 ;
cin >> option ;
}
return 0 ;
}

/*
Questions:

1.

Relevant Background information for my question:
===============================================

My documentation shows the range of values for a long
variable to be between -2147483648 to 2147483647 for
signed ones, and between 0 to 4294967295 unsigned ones.

however when I assigned a value 4294967295 to a long
variale at initialization, at compile time I get the
following warning message:

while_loop.c++:15: warning: decimal integer constant is so
large that it is unsigned

solution:
=========

I changed the statement:
unsigned long option = 4294967295
To:
unsigned long option = 4294967295UL and it worked.

Questions:
=========
a. Why did the statement "unsigned long option = (unsigned
long) 4294967295 ;" not work?
b. The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?
c. We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. Whatother type specifications are possible?

2. When I enter any nonumeric value into the variable option,
it results in an endless loop. Why does this happen?

*/


Thanks,
Raju


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Jason Hise
Guest





PostPosted: Sat Apr 16, 2005 5:39 pm    Post subject: Re: A few basic c++ questions Reply with quote




Raju wrote:
Quote:

When i try to create a character array with " in the intialization
code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning
messages
mean? Is the 'char *' in the warning indicative of a pointer
operation?


Yes. A character array (read c-style string) and a pointer to a
character are very closely related, and a character array can be
converted to a character pointer implicitly. Such a pointer refers to
element zero in the character array, and pointer arithmetic can be used
to find the location of any other character, because elements in an
array are contiguous in memory. Thus, assuming a character array named
str, the following lines are equivalent:

cout << str[5];
cout << *(str + 5);

Because a character is really just a byte sized integer (which is
usually used to hold an ascii value), a pointer to a character can be
converted to a character. This conversion of the numeric address in
memory to a byte sized integer looses information, and thus the
operation requires an explicit cast.


Quote:

Please explain the difference between nan and 200.000. why is nan
printed?

nan stands for "not a number". Floating point values can hold a few
special values, including not a number, and positive and negative
infinity. nan is most likely being printed because printf (and other
functions which use the elipsis) accept their arguments as a big bundle
of bits, losing all type safety. By failing to make the conversion to
a floating point number manually, the bits and alignment (padding) of
the parameter you are passing in are being misinterpreted as a floating
point number when that memory actually contains an integer. Because
the bitwise storage strategies for these types are different, you need
to do a conversion to a floating point value for the bits to be
interpreted correctly. Otherwise, you are essentially passing the
function garbage values.

Quote:

How am I able to use the function strcpy without including the
library file string.h?

workings. This is simply chance, and you should not rely upon it. By
the way, iostream.h is a non-standard header. The standard C++ headers
have no file extension, and scope their contents to the standard
namespace (meaning you should add the line "using namespace std;" under
your includes until you learn about namespaces).

Quote:
Why did the statement "unsigned long option =
(unsigned long) 4294967295 ;" not work?

The cast is performed after the temporary integral constant is created,
and that creation involves truncation.


Quote:
The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?

Any number without a decimal point and without a suffix will be
considered an int, and to my knowledge this is standard behavior.

Quote:
We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. What other type specifications are possible?

U, L, UL, LL, and ULL, are standard (yes, long long is a valid integral
type). Other suffixes or prefixes may exist as non standard compiler
extensions.

Quote:

When I enter any non numeric value into the variable option,
it results in an endless loop. Why does this happen?

I am making an educated guess, so someone feel free to correct me if I
am wrong. I suspect that this happens because when you attempt to read
a non numeric string into an integer, it puts the cin stream into an
error state. Any future input operations involving cin would silently
fail, and thus the loop would repeat indefinately. You can check cin's
error flags after attempting to read the number and possibly reset them
if nessecary so that the program could continue normally.

-Jason Hise


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Jack Klein
Guest





PostPosted: Sat Apr 16, 2005 5:41 pm    Post subject: Re: A few basic c++ questions Reply with quote



On 15 Apr 2005 20:09:45 -0400, "Raju" <Raju.K.Iyer (AT) gmail (DOT) com> wrote in
comp.lang.c++.moderated:

Quote:
I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

I am going to snip out all but the parts of your source code that
pertains to the question.

Quote:
1.
------------------------------------------------------

include <iostream.h
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning messages
mean? Is the 'char *' in the warning indicative of a pointer operation?

P.S

An expression of 0 or more characters enclosed in a pair of quotation
marks in C++ (or C) source code is a 'string literal'. In C++, the
compiler actually creates an unnamed array of constant char containing
the characters you put inside the quotations plus a '' terminator at
the end. Then it replaces the quoted string in the source code with a
pointer to the first character of the string.

So when you write "a" in your initializer, the compiler creates this:

const char (unnamed) [2] = { 'a', '' };

....and replaces the "a" in your code with a pointer to unnamed [0].
You cannot initialize a char, or any integer type, directly from a
pointer.

[snip]

Quote:
2.
------------------------------------------------------

#include
int main ()
{

unsigned int IntDisplay = 200 ;
unsigned long LongDisplay = 4294967295UL ;

[snip]

Quote:
printf ("Displaying value of IntDisplay using [%%*.*f]nWithout
casting IntDisplay to float type: %*.*fn",

[snip]

Quote:
}

/*
Output:

[snip]

Quote:
Displaying value of IntDisplay using [%*.*f]
Without casting IntDisplay to float type: nan

[snip]

Quote:
Question:

Please explain the difference between nan and 200.000. why is nan
printed?
*/

printf() is a variadic function. Only the first argument has a fixed
type, that of const char*. It may be called with a variable number
and types of arguments after the format string. There is no type
checking of these arguments to match the format string. It is up to
the programmer to pass the correct argument number and types. Passing
the wrong argument type causes undefined behavior, where anything can
happen.

You told printf() you were passing a double (floats always get
promoted to double in calls to variadic functions), but you passed it
an int instead. Your implementation happened to output the string
"nan" when you did that, but the C++ standard does not specify what
happens when you produce undefined behavior.

Quote:

3.
------------------------------------------------------
#include
char mybuffer [100] ;
char yourbuffer [100] ;

int main ()
{

cout << "Please enter a string: " ;
cin.getline(mybuffer, 10, 'n') ;
cout << "The value you entered is : " << mybuffer << "n" ;
strcpy(yourbuffer, mybuffer) ;
cout << "I copied the value you entered into a [yourbuffer] array :
" << yourbuffer << "n" ;
}

/*

Question:

How am I able to use the function strcpy without including the
library file string.h

The C++ language standard allows any standard C++ header to include
any other standard C++ header. You are using iostream.h, which is an
old C++ header and not part of the standard, but presumable it acts
the same way. On your compiler, iostream.h happens to include
string.h. Another compiler might not, and this code would not
compile.

Quote:
*/

4.
------------------------------------------------------


#include #include
int main (void)
{
//unsigned long option = 4294967295 ;
//unsigned long option = (unsigned long)4294967295 ;
unsigned long option = 4294967295UL ;

while (option != 0)
{
printf("The value of option is : %lun", option) ;
//cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
//option = 0 ;
cin >> option ;
}
return 0 ;
}

/*
Questions:

1.

Relevant Background information for my question:
===============================================

My documentation shows the range of values for a long
variable to be between -2147483648 to 2147483647 for
signed ones, and between 0 to 4294967295 unsigned ones.

however when I assigned a value 4294967295 to a long
variale at initialization, at compile time I get the
following warning message:

while_loop.c++:15: warning: decimal integer constant is so
large that it is unsigned

solution:
=========

I changed the statement:
unsigned long option = 4294967295
To:
unsigned long option = 4294967295UL and it worked.

Questions:
=========
a. Why did the statement "unsigned long option = (unsigned
long) 4294967295 ;" not work?

In C++ (and C), the type of a decimal integer literal without a suffix
in source code is a signed int if the value will fit in a signed int,
or a signed long if it will fit in a signed long. Decimal literals
are never converted to unsigned int or unsigned long. Only literals
written in hex or octal will be converted to unsigned it they will not
fit in a signed type.

The expression (unsigned long)4294967295 is first evaluated first as
an integer literal to produce a value, and then that value is cast to
unsigned long. 4294967295 is too large to fit into an int, so the
compiler tries to fit it into a signed long. But it will not fit into
a signed long, and the compiler is not allowed to put it into an
unsigned long. It overflows. After the overflow, you try to cast the
result to unsigned long, but it is already too late.

If you had written the value as 0xffffffff, the compiler would not
have complained because with hex notation it is allowed to evaluate
the literal as unsigned long if it is too large for signed long.

Quote:
b. The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?

The compiler assumes that all integer numeric constants are of type
signed int, unsigned int, signed long, or unsigned long if they are
written in hex or octal. If they are written in decimal, they are
evaluated as signed int or signed long only.

Quote:
c. We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. Whatother type specifications are possible?

The UL suffix changes the type of the literal to unsigned long. That
is it changes the type of the value, it doesn't evaluate it as signed
long and then convert the result to unsigned long, as the cast does.

As to suffixes, and book on C++ or C for that matter should cover
them.

Quote:
2. When I enter any nonumeric value into the variable option,
it results in an endless loop. Why does this happen?

This is a frequently asked question and covered in the FAQ. See the
link in my signature.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Bo Persson
Guest





PostPosted: Sat Apr 16, 2005 5:47 pm    Post subject: Re: A few basic c++ questions Reply with quote


"Raju" <Raju.K.Iyer (AT) gmail (DOT) com> skrev i meddelandet
news:1113595090.445874.71270 (AT) l41g2000cwc (DOT) googlegroups.com...
Quote:
I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

1.
------------------------------------------------------

include <iostream.h
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization
code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning
messages
mean? Is the 'char *' in the warning indicative of a pointer
operation?

The type of the string literal "a" is actually "const char[2]", which
sometimes may 'decay' to "const char *". For backward compatibility
with the C language, it might sometimes also be considered a "char*",
without the const.

You shouldn't really bother as to why. :-)


Quote:

P.S

I know that the correct way to setup and intialize the character array
is either:

char characters2[11] =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'n') ;

or
char characters2[11] = "abcdefghij" ;


2.
------------------------------------------------------

#include
int main ()
{

unsigned int IntDisplay = 200 ;
unsigned long LongDisplay = 4294967295UL ;

printf ("Displaying value of IntDisplay using [%%*.*d]: %*.*dn", 3,
10, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%0*d]: %0*dn", 10,
IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f]nWithout
casting IntDisplay to float type: %*.*fn",
10, 3, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f] nafter
casting IntDisplay to float type: %*.*fn",
10, 3, (float) IntDisplay) ;
printf ("Displaying value of LongDisplay using [%%*.*u]: %*.*un", 3,
10, LongDisplay) ;
return 0 ;

}

/*
Output:

Displaying value of IntDisplay using [%*.*d]: 0000000200
Displaying value of IntDisplay using [%0*d]: 0000000200

Displaying value of IntDisplay using [%*.*f]
Without casting IntDisplay to float type: nan

Displaying value of IntDisplay using [%*.*f]
after casting IntDisplay to float type: 200.000

Displaying value of LongDisplay using [%*.*u]: 4294967295

Question:

Please explain the difference between nan and 200.000. why is nan
printed?

200.000 is a float value.

nan means not-a-number, which indicates one kind of invalid floating
point value. In this case, you have tricked the compiler by mismatching
the format string and the values passed to the function. That breaks the
contract between the compiler and the programmer, and the compiler is
free to produce whatever it feels like.


This is also one reason for not using printf at all, but use the C++
operator<< instead. It is the compilers job to select the proper
overload of << for the type of your value. That relieves you from
interpreting things like "[%%*.*d]: %*.*dn".


Quote:
*/

3.
------------------------------------------------------

#include
char mybuffer [100] ;
char yourbuffer [100] ;

int main ()
{

cout << "Please enter a string: " ;
cin.getline(mybuffer, 10, 'n') ;
cout << "The value you entered is : " << mybuffer << "n" ;
strcpy(yourbuffer, mybuffer) ;
cout << "I copied the value you entered into a [yourbuffer] array :
" << yourbuffer << "n" ;
}

/*

Question:

How am I able to use the function strcpy without including the
library file string.h

By chance!

In C++ (but not in C) one header is allowed to include any other header
that iy needs. Here iostream.h obviously included string.h

Quote:

*/

4.
------------------------------------------------------


#include #include
int main (void)
{
//unsigned long option = 4294967295 ;
//unsigned long option = (unsigned long)4294967295 ;
unsigned long option = 4294967295UL ;

while (option != 0)
{
printf("The value of option is : %lun", option) ;
//cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
//option = 0 ;
cin >> option ;
}
return 0 ;
}

/*
Questions:

1.

Relevant Background information for my question:
===============================================

My documentation shows the range of values for a long
variable to be between -2147483648 to 2147483647 for
signed ones, and between 0 to 4294967295 unsigned ones.

however when I assigned a value 4294967295 to a long
variale at initialization, at compile time I get the
following warning message:

while_loop.c++:15: warning: decimal integer constant is so
large that it is unsigned

solution:
=========

I changed the statement:
unsigned long option = 4294967295
To:
unsigned long option = 4294967295UL and it worked.

Questions:
=========
a. Why did the statement "unsigned long option = (unsigned
long) 4294967295 ;" not work?

The C-style cast "(unsigned long)" tries to convert a value to the given
type. But first the compiler must find the original value. While doing
that, it noticed that what look like an int, really can't be because it
is outside the range of values allowed. The range supported by this
particular compiler should be specified in its documentation.

A number that is too large to be an int, can possibly be an unsigned
int, a long, or an unsigned long.


Generally, the "(some type)" style of casts are for experts only. It
tells the compiler "you should convert this value to this other type,
using whatever means necessary. Trust me, I know what I am doing!".

If you don't know exactly what you are doing, you may break the contract
with the compiler. Its job is to translate valid source code into an
executable. If you give it invalid code, but assures that it is valid,
you have released it from all responsibilities.

Quote:
b. The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?

A literal is considered an int, if it is in the range of possible
values.

Quote:
c. We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. Whatother type specifications are possible?

You can also use U for unsigned, or L for long. You also have F for
float values.

Quote:

2. When I enter any nonumeric value into the variable option,
it results in an endless loop. Why does this happen?


Because the operator >> tries to read a number, but stops as soon as the
next character cannot be part of a number. If it hasn't found any digits
in the input, it has no value to assign to option, so it doesn't. You
can check to status flags of cin to see if it has failed.


Bo Persson



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Thomas Maeder
Guest





PostPosted: Sat Apr 16, 2005 5:47 pm    Post subject: Re: A few basic c++ questions Reply with quote

"Raju" <Raju.K.Iyer (AT) gmail (DOT) com> writes:

Quote:
I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

Please next time make it one post per question, each with a
descriptive Subject: header.


Quote:
1.
------------------------------------------------------

include <iostream.h


If you are using a reasonably new compiler, it should offer
<iostream>, which is a Standard C++ header.

You'll then have to write std::cout etc., but you'll be writing
correct C++.


Quote:
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization
code for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast " a
bunch of times. This is pretty cryptic what do the warning messages
mean?

"a" is of type 'array of 2 char'. You are initializing an unsigned
char from it. That's very rarely a good idea.


Quote:
Is the 'char *' in the warning indicative of a pointer operation?

In C and C++, an array are implicitly converted into a pointer to its
first element in many contexts. The warning message seems to be based
on that implicit conversion.


Quote:
I know that the correct way to setup and intialize the character array
is either:

char characters2[11] =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'n') ;

or
char characters2[11] = "abcdefghij" ;

I hope that you are aware that these two initializations are not
equivalent. The latter will initialize the 11th element with '', not
'n'.


Quote:
#include
int main ()
{

unsigned int IntDisplay = 200 ;
unsigned long LongDisplay = 4294967295UL ;

printf ("Displaying value of IntDisplay using [%%*.*d]: %*.*dn", 3,
10, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%0*d]: %0*dn", 10,
IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f]nWithout
casting IntDisplay to float type: %*.*fn",
10, 3, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f] nafter
casting IntDisplay to float type: %*.*fn",
10, 3, (float) IntDisplay) ;
printf ("Displaying value of LongDisplay using [%%*.*u]: %*.*un", 3,
10, LongDisplay) ;
return 0 ;

}

/*
Output:

Displaying value of IntDisplay using [%*.*d]: 0000000200
Displaying value of IntDisplay using [%0*d]: 0000000200

Displaying value of IntDisplay using [%*.*f]
Without casting IntDisplay to float type: nan

Displaying value of IntDisplay using [%*.*f]
after casting IntDisplay to float type: 200.000

Displaying value of LongDisplay using [%*.*u]: 4294967295

Question:

Please explain the difference between nan and 200.000. why is nan
printed?
*/

Your program has undefined behavior. The format string passed to
printf() doesn't match the subsequent arguments in that call. Anything
can happen, including nan to be written.

The printf() family of functions is type-unsafe. Errors like this led
to the development of the are required.


Quote:
3.
------------------------------------------------------

#include <iostream.h

char mybuffer [100] ;
char yourbuffer [100] ;

int main ()
{

cout << "Please enter a string: " ;
cin.getline(mybuffer, 10, 'n') ;
cout << "The value you entered is : " << mybuffer << "n" ;
strcpy(yourbuffer, mybuffer) ;
cout << "I copied the value you entered into a [yourbuffer] array :
" << yourbuffer << "n" ;
}

/*

Question:

How am I able to use the function strcpy without including the
library file string.h

*/

You are not. What problem are you trying to solve?


Quote:
4.
------------------------------------------------------

#include #include
int main (void)
{
//unsigned long option = 4294967295 ;
//unsigned long option = (unsigned long)4294967295 ;
unsigned long option = 4294967295UL ;

while (option != 0)
{
printf("The value of option is : %lun", option) ;
//cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
//option = 0 ;
cin >> option ;
}
return 0 ;
}

/*
Questions:

1.

Relevant Background information for my question:
===============================================

My documentation shows the range of values for a long
variable to be between -2147483648 to 2147483647 for
signed ones, and between 0 to 4294967295 unsigned ones.

however when I assigned a value 4294967295 to a long
variale at initialization, at compile time I get the
following warning message:

while_loop.c++:15: warning: decimal integer constant is so
large that it is unsigned

solution:
=========

I changed the statement:
unsigned long option = 4294967295
To:
unsigned long option = 4294967295UL and it worked.

Questions:
=========
a. Why did the statement "unsigned long option = (unsigned
long) 4294967295 ;" not work?

By default, integer literals, like 17, have type int. If an integer
literal doesn't fit into an int object, but fits into a long object,
it's type is long. If its type doesn't even fit into a long object,
but fits into an unsigned long object, its type is unsigned long.

Only after these considerations comes the cast "(unsigned long)" into
play.


Quote:
b. The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?

int


Quote:
c. We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. Whatother type specifications are possible?

Any reasonable C or C++ textbook contains information like
this. Please see to the book reviews at http://www.accu.org/ to find
out which textbooks are reasonable.


Quote:
2. When I enter any nonumeric value into the variable option,
it results in an endless loop. Why does this happen?

Because your program is incorrect.

The operation

cin >> option

can fail (in the described case, it does). You should check for that,
e.g.:

do
{
cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
} while ((cin >> option) && (option!=0));

This will terminate the loop if the input operation failes or if the
user entered 0.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Alberto Barbati
Guest





PostPosted: Sun Apr 17, 2005 6:05 pm    Post subject: Re: A few basic c++ questions Reply with quote

Raju wrote:
Quote:
I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

1.
------------------------------------------------------

include <iostream.h

First problem. It seems that you are learning C++ on a very old book.
#include includes a non-standard version of the iostream library. You should
always use include <iostream> (without the ".h") instead.

Moroever, I *strongly* recommend that you buy a newer book.

Quote:
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;

Using #include namespace so you will need to use std::cout instead.

Quote:
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning messages
mean? Is the 'char *' in the warning indicative of a pointer operation?

'a' is a character literal, whose value is an integral of type char.

<Newbie mode>
"a" is a string literal, whose value is a pointer to the first character
of a string of two characters (an 'a' and a ''). As it's a pointer, it
cannot be converted to unsigned char.
</Newbie mode>

<Expert mode>
"a" is a string literal, whose value is a const char[2] initialized to
{'a',''} and decays to a pointer of type const char* (although it can
be converted to char* in certain contexts). In any case it cannot be
converted to unsigned char.

BTW, you seem to be using a non-conformant, probably very old, compiler,
as from the error message it seems that it is interpreting "a" as a
char* and not as a const char[2]. Old compilers did that. I *strongly*
recommend that you learn the language on a newer compiler.
</Expert mode>

Quote:

2.
------------------------------------------------------

#include <stdio.h

Although you *can* use include recommended that you include <cstdio> instead.

(Notice that the use of <iostream> instead of <iostream.h> is mandatory
and is *not* a recommendation!!)

Quote:

int main ()
{

unsigned int IntDisplay = 200 ;
unsigned long LongDisplay = 4294967295UL ;

printf ("Displaying value of IntDisplay using [%%*.*d]: %*.*dn", 3,
10, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%0*d]: %0*dn", 10,
IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f]nWithout
casting IntDisplay to float type: %*.*fn",
10, 3, IntDisplay) ;
printf ("Displaying value of IntDisplay using [%%*.*f] nafter
casting IntDisplay to float type: %*.*fn",
10, 3, (float) IntDisplay) ;
printf ("Displaying value of LongDisplay using [%%*.*u]: %*.*un", 3,
10, LongDisplay) ;
return 0 ;

}

/*
Output:

Displaying value of IntDisplay using [%*.*d]: 0000000200
Displaying value of IntDisplay using [%0*d]: 0000000200

Displaying value of IntDisplay using [%*.*f]
Without casting IntDisplay to float type: nan

Displaying value of IntDisplay using [%*.*f]
after casting IntDisplay to float type: 200.000

Displaying value of LongDisplay using [%*.*u]: 4294967295

Question:

Please explain the difference between nan and 200.000. why is nan
printed?

This is a C question not a C++ one, because printf is included in C++
only for C compatibility and is better avoided in C++ programs. The
reason for this is exactly that is very error-prone. Yours is a very
good example of that. The explanation of why nan is displayed is quite
complex and relates to the implementation of varadic functions which is
platform-specific. I prefer not going into the details.

Quote:
3.
------------------------------------------------------

#include <iostream.h

char mybuffer [100] ;
char yourbuffer [100] ;

int main ()
{

cout << "Please enter a string: " ;
cin.getline(mybuffer, 10, 'n') ;
cout << "The value you entered is : " << mybuffer << "n" ;
strcpy(yourbuffer, mybuffer) ;
cout << "I copied the value you entered into a [yourbuffer] array :
" << yourbuffer << "n" ;
}

/*

Question:

How am I able to use the function strcpy without including the
library file string.h

Because not rely on this fact however, good programming style requires that you
always include all headers that you are going to need.

Quote:

4.
------------------------------------------------------


#include <iostream.h
#include
int main (void)
{
//unsigned long option = 4294967295 ;
//unsigned long option = (unsigned long)4294967295 ;
unsigned long option = 4294967295UL ;

while (option != 0)
{
printf("The value of option is : %lun", option) ;
//cout << "The value of option is : " << option << "n" ;
cout << "Please enter 0 to exit. any other # to continue: " ;
//option = 0 ;
cin >> option ;
}
return 0 ;
}

/*
Questions:

1. <snip

Questions:
=========
a. Why did the statement "unsigned long option = (unsigned
long) 4294967295 ;" not work?
b. The compiler assumes that the type of all numeric
constants is int or short (which one?) Is this correct?

An integer literal without suffix can only be of type int or long int
(in particular, it's never unsigned). If the value cannot be represented
as a long int, the behavior is undefined (it's all in the standard, see
clause §2.13.1 paragraph 2). Your compiler seems smart enough to assume
that you meant to specify an unsigned value but emits a warning to...
warn you. It could have rejected the code and that would have been
perfectly ok from the C++ Standard point of view.

Quote:
c. We used UL after the numeric constant to tell the
compiler that the number is an unsinged long
constant. Whatother type specifications are possible?

You can use "u" for unsigned and "l" for long. Case is unimportant as
it's the order: "ul", "lu", "Lu" etc. are all valid. Notice that you
cannot make a integer literal of type short or unsigned short.

Implementations that supports (as an extension to C++) long long types,
may also have "ll" and "ull".

Quote:

2. When I enter any nonumeric value into the variable option,
it results in an endless loop. Why does this happen?

Because "cin >> option" fails. Because of this, the read operation
leaves option unchanged and puts the stream in "fail" state. When a
stream is in "fail" state any subsequent attempt to read will again fail
immediately, until the stream state is cleared. That's why good
programming style suggests to check the stream state in the loop test:

while (cin.good() && option != 0)
{
printf("The value of option is : %lun", option) ;
cin >> option;
}

or even better (but the meaning changes slightly):

while (cin >> option)
{
printf("The value of option is : %lun", option) ;
}

avoid the dreaded and error-prone printf for an extra point:

while (cin >> option)
{
cout << "The value of option is : " << option << "n" ;
}

HTH,

Alberto

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
James Jennings
Guest





PostPosted: Sun Apr 17, 2005 9:09 pm    Post subject: Re: A few basic c++ questions Reply with quote

Raju wrote:
Quote:
I am new to c++. and am learnig it on my own. I would appreciate it if
any one could give me answers to the following 4 questions. I have put
the code followed by the questions for each one.

1.
------------------------------------------------------

include <iostream.h
//source code x.c++
int main ()
{
unsigned char characters2 [10] =
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is
: " << characters[i] << "n" ;
}
return 0 ;
}

/*
Question :

When i try to create a character array with " in the intialization code
for the array I get the warning message "x.c++:17: warning:
initialization to `unsigned char' from `char *' lacks a cast
" a bunch of times. This is pretty cryptic what do the warning messages
mean? Is the 'char *' in the warning indicative of a pointer operation?

P.S

I know that the correct way to setup and intialize the character array
is either:

char characters2[11] =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'n') ;

or
char characters2[11] = "abcdefghij" ;


First question first.

There are several things wrong with the code:
a. the first line should be: #include the # is necessary, and for C++ use <iostream> rather than
<iostream.h>
b. for the cout statement you must say std::cout, or use either the
"using namespace std;" or "using std::cout;" statement. (without
quotes.)
c. you declare the array as characters2[10], but use characters[i]
in the cout statement. characters[] does not exist.
d you have to use characters in the array not strings: 'a' not "a".
e you have 11 initializers in a 10 element array. If you initialize
the array when declaring it, you don't need the [10], [] is enough.
The compiler will allocate space for as many elements as you have
initializers What is the newline initializer supposed to do?

Some of these corrections are very basic C++. Your program demonstrates
that your grasp of C++ is shaky. You either need to take a course, get a
mentor who knows C++ to help you, or at least find a good book, and read
it carefully and repeatedly. It also helps to copy the code from your
book with your text editor. That helps focus your attention on points
you may have missed in your reading. Also read others' code, and look up
everything you cannot understand. If the code is too complicated, find
something simpler. Learning C++ takes much work and a long time.

The following compiles and runs on the gnu C++ compiler.

#include <iostream>
//source code x.c++

using std::cout;

int main ()
{
unsigned char characters[] =
{'a','b','c','d','e','f','g','h','i','j'} ;

for (int i =0; i < 10; i++)
{
cout << "The value of the array element characters[" << i << "] is:
"
<< characters[i] << "n" ;
}
return 0 ;
}

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Alberto Barbati
Guest





PostPosted: Sun Apr 17, 2005 9:10 pm    Post subject: Re: A few basic c++ questions Reply with quote

Thomas Maeder wrote:
Quote:
"Raju" <Raju.K.Iyer (AT) gmail (DOT) com> writes:


By default, integer literals, like 17, have type int. If an integer
literal doesn't fit into an int object, but fits into a long object,
it's type is long. If its type doesn't even fit into a long object,
but fits into an unsigned long object, its type is unsigned long.

This is not correct. An unsuffixed decimal integer literal has never
type unsigned long (see §2.13.1/2). That's the problem the OP is
experiencing, because the literal 4294967295 overflows (cannot be
neither an int nor a long).

Alberto

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
kanze@gabi-soft.fr
Guest





PostPosted: Mon Apr 18, 2005 11:01 am    Post subject: Re: A few basic c++ questions Reply with quote

James Jennings wrote:

[...]
Quote:
The following compiles and runs on the gnu C++ compiler.

But not necessarily on all C++ compilers.

Quote:
#include <iostream

You later use the << operator. This is not formally defined in
<iostream> include <ostream>.

Several posters have indicated that he should use <iostream>
instead of <iostream.h>. This is generally good advice;
<iostream> is the standard, and it is available in all recent
compilers (and while there are often good reasons for using an
older compiler, you shouldn't do so while you are still learning
the basics). But it's important to point out as well that the
<< operator is in to use it, you should include <ostream>. (In typical projects,
as opposed to one source file demo programs and experiments,
it's actually rather rare to include <iostream>. Most of the
time, you're outputting to an ostream that someone has passed as
a parameter, so you need <<, but not std::cout.)

--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.