-2
#include <iostream>
using namespace std;
int main() {
    int age = 20;
    const char* pDept = "electronics";
    cout << age << " " << pDept;
}

The above code is normal.

Why shouldn't I use cout << *pDept instead of cout << pDept above?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • _"Why shouldn't I use cout << *pDept instead of cout << pDept above?"_ because that would print only the 1st character of the literal. – πάντα ῥεῖ Sep 24 '22 at 07:31
  • 1
    a `const char *` string is an array of `char` (`null` terminated). By dereferencing, you will get the first `char` – Angelos Gkaraleas Sep 24 '22 at 07:33
  • In some circumstances (like printing) C++ treats `char*` as a special case meaning a nul terminated string. But if you said `*pDept` then you should have `char` and that means a **single** character, in your case that would print just `e`. – john Sep 24 '22 at 07:45
  • *"Why shouldn't I use cout << *pDept..."* You could use that. Who said you shouldn't? – Jason Sep 24 '22 at 07:57

1 Answers1

2

Both of them are legal in C++. Which one to use depends on what you want to print.

In your case, pDept is a pointer that points to a char in memory. It also can be used as a char[] terminated with \0. So std::cout << pDept; prints the string the pointer is pointing to.

*pDept is the content that pDept points to, which is the first character of the string. So std::cout << *pDept; prints the first character only.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
sxu
  • 151
  • 5