C - Using pointers to display a string

Introduction

C has no string variable and it uses the char array to store a string.

Demo

#include <stdio.h>

int main()// w  w w.j a  va  2  s  .c o  m
{
    char sample[] = "this is a test?\n";
    char *ps = sample;

    while(*ps != '\0')
    {
        putchar(*ps);
        ps++;
    }
    return(0);
}

Result

Eliminating the redundant comparison.

Demo

#include <stdio.h>

int main()//w  w w . ja  va 2 s.  c  o m
{
    char sample[] = "this is a test?\n";
    char *ps = sample;

    while(*ps)
        putchar(*ps++);
    return(0);
}

Result

Eliminate the statements in the while loop. Place all the action in the while statement's evaluation.

putchar() function returns the character that's displayed.

Demo

#include <stdio.h>

int main()//from  w  w  w. j a  v a  2s.  com
{
    char sample[] = "this is a test?\n";
    char *ps = sample;

    while(putchar(*ps++))
        ;
    return(0);
}

Result

Related Topic