I am currently going through the 5th edition of C++ Primer by Lahoie, Lippman and Moo and have been struggling with a few things.
Firstly, I just wanted to confirm, when using any of the cctype
functions, I have to make sure I include the header, right? Because, initially, I forgot to include it and yet it still ran. That's really confused me.
Also, I was browsing for a different problem (which I'll get to) and found another issue haha! When using anything from cctype
, are I supposed to write it as std::/write using std::
, e.g. if I use the tolower
either write std::tolower
at every instance/write a using statement for it. This would make sense as it did say that they are "defined in the std
namespace" but I didn't realise and have been writing it without and haven't had an issue. And I'm guessing similar for size_t
, right?
Speaking of size_t
, I have an issue. This is my code:
// Exercise Section 3.5.2., Exercise 3.30
#include <iostream>
#include <cstddef>
using std::cout; using std::endl;
int main()
{
constexpr size_t num_size = 10;
int num[num_size] = {};
for (size_t n = 0; n < num_size; ++n) {
num[n] = n;
cout << num[n] << endl;
}
return 0;
}
So the code is supposed define an array of 10 int
s and give each element the same value as its position in the array.
It runs correctly, but I am receiving an error at the num[n]=n
part. It says Implicit conversion loses integer precision: size_t (aka 'unsigned long') to int
.
I understand what this means, but my issue is that the book says "when we use a variable to subscript an array, we normally should define that variable to type size_t
". I have done this and it gives this error. It does run fine but it seems like that sort of thing that can lead to errors.
P.S. In this code, like I asked above, should I have using std::size_t
?