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()//from   w w  w.j av  a  2s  .  com
{
    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()//from   w  ww  .ja  v a  2  s .co  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  .  ja v a  2  s.co m*/
{
    char sample[] = "this is a test?\n";
    char *ps = sample;

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

Result

Related Topic