Hey guys, this is my first post and I would like to say thank you to all of you guys out there that are doing such a great job with helping out on this forum.

Anyway, lets get to the question. Why, in the code below, does the char values that are sent to the functions change in both the void functions and the main function if there is no call-by-reference (&) operator used?

#include <iostream>
#include <cstring>
using namespace std;

// void convertToLowerCase(char name[])
// Pre: name[] contains a C-string
// Post: name[] has been converted to lower case
void convertToLowerCase(char name[])

//void pigLatin(char name[])
// Pre: name[] contains a C-string
// Post: name[] has been converted to pig latin
void pigLatin(char name[])

int main()
  char first[21], last[21], newName[41], copyFirst[21], copyLast[21];
  cout << "Please enter your first name: ";
  cin >> first;
  cout << "Please enter your last name: ";
  cin >> last;
  //make a copy of the first and last name for output purposes
  strcpy(copyFirst, first);
  strcpy(copyLast, last);
  //convert first and last name to lowercase
  //convert first and last name to pig latin

  //create new string with first and last name in pig latin
  strcpy(newName, first);
  strcat(newName, " "); //add space between first and last name
  strcat(newName, last);
  cout << "Dear " << copyFirst << " " << copyLast
  << " in pig latin your name is " << newName << endl;
  return 0;

void convertToLowerCase(char name[])
  int i = 0;
  while (name[i] != '\0')
    name[i] = tolower(name[i]);

void pigLatin(char name[])
  char ch;
  if ((name[0] == 'a') || (name[0] == 'e') || (name[0] == 'i')
  || (name[0] == '0') || (name[0] == 'u'))
    name[0] = toupper(name[0]);
    strcat(name, "way");
    ch = name[0];
    for (int i = 0; i <= strlen(name); i++)
    name[i] = name[i+1];
    name[strlen(name)] = ch;
    strcat(name, "ay");
    name[0] = toupper(name[0]);
9 Years
Discussion Span
Last Post by ArkM

You are actually passing the array by reference, although you aren't using the & operator. When you say this: convertToLowerCase(first); You're actually saying this: convertToLowerCase(&first[0]); and voila: pass by reference :)


You don't pass "char by reference" to these functions. You pass (as usually by value, not by reference) a pointer to char: feel the difference. Look at "pass char by reference" case:

void PassCharByRef(char& c);

Don't mix distinct types: array of char and char.

About array case: there is implicit conversion defined in C++ (and C). In all contexts (except argument of operator sizeof) an array name converts to a pointer to base type which refers to the 1st element of an array.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.