Home » Programming Tips & Tricks » C - Tips & Tricks

How should we declare/define a pointer variable?

By: IncludeHelp, on 08 FEB 2017

Here, I am writing about pointer declaration/definition rule, which style should be used among many styles of pointer declaration/definition?

In the pointer declarations/definitions, a common confusion about placing asterisk (*) sign, it can be placed close to the data type, after the data type and close to the pointer name.

int* ptr;
int * ptr;
int *ptr;

Recommended style of pointer declaration/definition

Style 3 (int *ptr;) is highly recommended that means - Asterisk (*) sign should be placed close to the pointer name.

This style is highly understandable as we can clear see that which variable is the pointer variable, so you should always use this style.

It is also helpful, when you are declaring pointer and normal variable together, let suppose you want to declare an integer variable and an integer pointer, then we can use this style to declare/define these variables.

int var, *ptr;

In this statement ptr is a pointer variable, while var is a normal integer variable.

Consider the given example:

#include <stdio.h>
int main()
	int var,*ptr;
	printf("var= %d\n",*ptr);
	return 0;


var= 10

In this program, there are two variables ptr as integer pointer and var as integer variable, both are declared using a single declaration statement int var, *ptr;

As you can see the declaration, it is cleared that var is an integer variable (because it does not contain * with the variable name) and ptr is an integer pointer (because it contains * with the ptr).

I would recommend using this style of pointer declaration.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.