swaroop reddy
swaroop reddy

Reputation: 21

i am trying to understand how formal parameters work in c++

I am new to programming, trying to understand what formal parameters are. I am reading this book called "the complete c++ reference", there is an example provided in the book about formal parameters which I am attaching in the code below. when I try to execute the program a list of errors is being displayed can anyone explain where I am going wrong.

Code from book

/* Return 1 if c is part of string s; 0 otherwise */
int is_in(char *s, char c) {
  while(*s)
    if (*s==c)
      return 1;
    else
      s++;
  return 0;
}

Program which I am trying to execute

#include <iostream>
#include <stdio.h>


int is_in(char* s, char c){
  while(s)
    if(s==c)
      return 1;
    else
       s++;
  return 0;
};

char* s = (char*)"flying";
char c;

int main(void){      
  is_in(s, 'g');
}

Upvotes: 0

Views: 220

Answers (1)

Tharun K
Tharun K

Reputation: 1180

The issue is at

 while(s)
    if(s==c)return 1;

s is a char pointer, in order to get the value stored at the memory to which the pointer s is pointing, you must de-reference it by using a * operator as shown in the example

    while(*s)
       if(*s==c) return 1;
#include <iostream>

int
is_in(char * s, char c) {
  while ( * s)
    if ( * s == c)
      return 1;
    else
      s++;
  return 0;
};

char * s = (char * )
"flyin";

char c;

int
main(void) {
  is_in(s, 'g');
  return 0;
}

Upvotes: 2

Related Questions