Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Why declare a variable in one line, and assign to it in the next?

I often see in C and C++ code the following convention:

I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I've learned not to dismiss so quickly the habits of veteran developers. So, is there a good reason for declaring in one line, and assigning afterwards?

Robert Harvey's user avatar

  • 15 +1 for "I've learned not to dismiss so quickly the habits of veteran developers." That's a wise lesson to learn. –  Wildcard Commented Nov 30, 2015 at 15:56

7 Answers 7

In C89 all declarations had to be be at the beginning of a scope ( { ... } ), but this requirement was dropped quickly (first with compiler extensions and later with the standard).

These examples are not the same. some_type val = something; calls the copy constructor while val = something; calls the default constructor and then the operator= function. This difference is often critical.

Some people prefer to first declare variables and later define them, in the case they are reformatting their code later with the declarations in one spot and the definition in an other.

About the pointers, some people just have the habit to initialize every pointer to NULL or nullptr , no matter what they do with that pointer.

orlp's user avatar

  • 1 Great distinction for C++, thanks. What about in plain C? –  Jonathan Sterling Commented May 7, 2011 at 20:35
  • 14 The fact that MSVC still doesn't support declarations except at the beginning of a block when it's compiling in C mode is the source of endless irritation for me. –  Michael Burr Commented May 7, 2011 at 22:03
  • 5 @Michael Burr: This is because MSVC doesn't support C99 at all. –  orlp Commented May 7, 2011 at 22:05
  • 4 "some_type val = something; calls the copy constructor": it may call the copy constructor, but the Standard allows the compiler to elide the default-construction of a tempory, copy construction of val and destruction of the temporary and directly construct val using a some_type constructor taking something as sole argument. This is a very interesting and unusual edge case in C++... it means there's a presumption about the semantic meaning of these operations. –  Tony Commented May 9, 2011 at 9:15
  • 2 @Aerovistae: for built-in types they are the same, but the same can not always be said for user-defined types. –  orlp Commented Oct 11, 2012 at 18:48

You have tagged your question C and C++ at the same time, while the answer is significantly different in these languages.

Firstly, the wording of the title of your question is incorrect (or, more precisely, irrelevant to the question itself). In both of your examples the variable is declared and defined simultaneously, in one line. The difference between your examples is that in the first one the variables are either left uninitialized or initialized with a dummy value and then it is assigned a meaningful value later. In the second example the variables are initialized right away.

Secondly, in C++ language, as @nightcracker noted in his answer these two constructs are semantically different. The first one relies on initialization while the second one - on assignment. In C++ these operations are overloadable and therefore can potentially lead to different results (although one can note that producing non-equivalent overloads of initialization and assignment is not a good idea).

In the original standard C language (C89/90) it is illegal to declare variables in the middle of the block, which is why you might see variables declared uninitialized (or initialized with dummy values) at the beginning of the block and then assigned meaningful values later, when those meaningful values become available.

In C99 language it is OK to declare variables in the middle of the block (just like in C++), which means that the first approach is only needed in some specific situations when the initializer is not known at the point of declaration. (This applies to C++ as well).

AnT stands with Russia's user avatar

  • 2 @Jonathan Sterling: I read your examples. You probably need to brush up on the standard terminology of C and C++ languages. Specifically, on the terms declaration and definition , which have specific meanings in these languages. I'll repeat it again: in both of your examples the variables are declared and defined in one line. In C/C++ the line some_type val; immediately declares and defines the variable val . This is what I meant in my answer. –  AndreyT Commented May 7, 2011 at 20:53
  • 1 I see what you mean there. You're definitely right about declare and define being rather meaningless the way I used them. I hope you accept my apologies for the poor wording, and poorly-thought-out comment. –  Jonathan Sterling Commented May 7, 2011 at 20:55
  • 1 So, if the consensus is that “declare” is the wrong word, I'd suggest that someone with a better knowledge of the standard than me edit the Wikibooks page. –  Jonathan Sterling Commented May 7, 2011 at 21:11
  • 2 In any other context declare would be the right word, but since declare is a well-defined concept , with consequences, in C and C++ you can not use it as loosely as you could in other contexts. –  orlp Commented May 7, 2011 at 21:15
  • 2 @ybungalobill: You are wrong. Declaration and definition in C/C++ is not mutually exclusive concepts. Actually, definition is just a specific form of declaration . Every definition is a declaration at the same time (with few exceptions). There are defining declarations (i.e. definitions) and non-defining declarations. Moreover, normally the therm declaration is used all the time (even if it is a definition), except for the contexts when the distinction between the two is critical. –  AndreyT Commented May 7, 2011 at 21:52

I think it's an old habit, leftover from "local declaration" times. And therefore as answer to your question: No I don't think there's a good reason. I never do it myself.

I said something about that in my answer to a question by Helium3 .

Basically, I say it's a visual aid to easily see what is changed.

Community's user avatar

The other answers are pretty good. There's some history around this in C. In C++ there's the difference between a constructor and an assignment operator.

I'm surprised no one mentions the additional point: keeping declarations separate from use of a variable can sometimes be a lot more readable.

Visually speaking, when reading code, the more mundane artifacts, such as the types and names of variables, are not what jump out at you. It's the statements that you're usually most interested in, spend most time staring at, and so there's a tendency to glance over the rest.

If I have some types, names, and assignment all going on in the same tight space, it's a bit of information overload. Further, it means that something important is going on in the space that I usually glance over.

It may seem a bit counter-intuitive to say, but this is one instance where making your source take up more vertical space can make it better. I see this as akin to why you shouldn't write jam-packed lines which do crazy amounts of pointer arithmetic and assignment in a tight vertical space -- just because the language lets you get away with such things doesn't mean you should do it all the time. :-)

asveikau's user avatar

In C, this was the standard practice because variables had to be declared at the start of the function, unlike in C++, where it could be declared anywhere in the function body to be used thereafter. Pointers were set to 0 or NULL, because it just made sure that the pointer pointed to no garbage. Otherwise, there's no significant advantage that I can think of, which compels anyone to do like that.

Vite Falcon's user avatar

Pros for localising variable definitions and their meaningful initialisation:

if variables are habitually assigned a meaningful value when they first appear in the code (another perspective on the same thing: you delay their appearance until a meaningful value is avaialable) then there's no chance of them accidentally being used with a meaningless or uninitialised value (which can easily happen is some initialisation is accidentally bypassed due to conditional statements, short-circuit evaluation, exceptions etc.)

can be more efficient

  • avoids overheads of setting initial value (default construction or initialisation to some sentinel value like NULL)
  • operator= can sometimes be less efficient and require a temporary object
  • sometimes (esp. for inline functions) the optimiser can remove some/all inefficiencies

minimising the scope of variables in turn minimises average number of variables concurrently in scope : this

  • makes it easier to mentally track the variables in scope, the execution flows and statements that might affect those variables, and the import of their value
  • at least for some complex and opaque objects, this reduces resource usage (heap, threads, shared memory, descriptors) of the program

sometimes more concise as you're not repeating the variable name in a definition then in an initial meaningful assignment

necessary for certain types such as references and when you want the object to be const

Arguments for grouping variable definitions:

sometimes it's convenient and/or concise to factor out the type of a number of variables:

the_same_type v1, v2, v3;

(if the reason is just that the type name is overly long or complex, a typedef can sometimes be better)

sometimes it's desirable to group variables independently of their usage to emphasise the set of variables (and types) involved in some operation:

type v1; type v2; type v3;

This emphasises the commonality of type and makes it a little easier to change them, while still sticking to a variable per line which facilitates copy-paste, // commenting etc..

As is often the case in programming, while there can be a clear empirical benefit to one practice in most situations, the other practice really can be overwhelmingly better in a few cases.

Tony's user avatar

  • I wish more languages would distinguish the case where code declares and sets the value of a variable which would never be written elsewhere, though new variables could use the same name [i.e. where behavior would be the same whether the later statements used the same variable or a different one], from those where code creates a variable that must be writable in multiple places. While both use cases will execute the same way, knowing when variables may change is very helpful when trying to track down bugs. –  supercat Commented Apr 28, 2014 at 22:50

Not the answer you're looking for? Browse other questions tagged c++ c or ask your own question .

  • The Overflow Blog
  • Is this the real life? Training autonomous cars with simulations
  • What launching rockets taught this CTO about hardware observability
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Stick lodging into front wheel - is it preventable?
  • Is grounding an outlet only to its box enough?
  • What was Adam Smith's position on the American Revolution?
  • In what Disney film did a gelatinous cube appear?
  • Does painting or staining a fence make it last longer?
  • Simple console calculator app. Looking for structure/best practices tips
  • A curious norm related to the L¹ norm
  • Equation numbering doesn't start at 1 for alignat inside minipage inside tabularray
  • "Almost true": non-trivial claims that have exactly one counterexample
  • Non-commuting elements of finite orders in a reductive group over a p-adic field
  • How good is Quicken Spell as a feat?
  • What expressions (verbs) are used for the actions of adding ingredients (solid, fluid, powdery) into a container, specifically while cooking?
  • Recursively move subtitle files into subdirectories
  • bind_rows on a list fails if some sub-list elements are empty. Why?
  • Is there a security vulnerability in Advanced Custom Fields related to the SCF fork?
  • Why the title The Silver Chair?
  • Belief in Teshuvah being a prerequisite
  • Are these superheroes plagiarised?
  • SSL certificate working ok on Firefox but not for Chrome
  • Offering shelter to homeless employees
  • Customize the man command's status prompt to show percentage read
  • Book about a homeless girl who volunteers at a shady facility for money
  • How to reduce the precision of a shape without creating duplicated points?
  • What happens in a game where one side has a minor piece and the other side has a rook or a pawn and is flagged on time?

c declaration vs assignment

Technical Questions and Answers

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Explain the variable declaration, initialization and assignment in C language

The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution.

The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.

Variable declaration

The syntax for variable declaration is as follows −

For example,

Here, a, b, c, d are variables. The int, float, double are the data types.

Variable initialization

The syntax for variable initialization is as follows −

Variable Assignment

A variable assignment is a process of assigning a value to a variable.

Rules for defining variables

A variable may be alphabets, digits, and underscore.

A variable name can start with an alphabet, and an underscore but, can’t start with a digit.

Whitespace is not allowed in the variable name.

A variable name is not a reserved word or keyword. For example, int, goto etc.

Following is the C program for variable assignment −

 Live Demo

When the above program is executed, it produces the following result −

Bhanu Priya

  • Related Articles
  • Initialization, declaration and assignment terms in Java
  • Explain variable declaration and rules of variables in C language
  • Variable initialization in C++
  • What is the difference between initialization and assignment of values in C#?
  • Structure declaration in C language
  • Explain the accessing of structure variable in C language
  • Explain scope of a variable in C language.
  • Explain Lifetime of a variable in C language.
  • Explain Binding of a variable in C language.
  • Initialization of variable sized arrays in C
  • MySQL temporary variable assignment?
  • Explain Compile time and Run time initialization in C programming?
  • Rules For Variable Declaration in Java
  • Explain the Difference Between Definition and Declaration
  • Java variable declaration best practices

Kickstart Your Career

Get certified by completing the course

Differences Between Definition, Declaration, and Initialization

Last updated: March 18, 2024

c declaration vs assignment

  • Programming
  • Compilers and Linkers

announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Introduction

In this tutorial, we’ll explain the differences between definition, declaration, and initialization in computer programming.

The distinction between the three concepts isn’t clear in all languages. It depends on the language we’re coding in and the thing we want to declare, define or initialize.

2. Declarations

A declaration introduces a new identifier into a program’s namespace. The identifier can refer to a variable, a function, a type , a class, or any other construct the language at hand allows.

For a statement to be a declaration, it only needs to tell us what the declared identifier is. After reading a declaration statement, the code processor ( compiler or interpreter ) can differentiate between legal and illegal uses of the identifier.

For example, in C, we can declare a function by specifying its signature or a variable by specifying its type:

We see that g is a function with an integer argument and no return value. Similarly, x is an integer variable. That’s everything a compiler needs to know about g and x to report incorrect use. For instance, x(g) would raise a compiler error, whereas g(x) wouldn’t.

Other languages work the same. Their syntax rules may differ, but none allows us to use an identifier before declaring it.

2.1. Formal Languages

2.2. what declarations can’t do.

A declaration tells us what an identifier is. That isn’t enough.

Let’s go back to the above example. We can say that our C compiler wouldn’t complain about statements such as g(5) . However, g doesn’t have a body specifying the operations it applies to its argument. As a result, we can’t execute any statement involving g , so we’ll get a runtime error if we try.

In other words, declaring an identifier doesn’t guarantee its existence during the runtime. It’s our job to make sure that’s the case by defining it.

3. Definitions

When defining an identifier, we instruct the code processor to allocate , i.e., reserve a sufficiently large memory chunk for it. That means and requires different things depending on the identifier’s type.

For example, to define a function, we need to write its body. When handling the function’s definition, the processor converts it into machine code , places it in the reserved space, and links the function’s name to the place in memory containing the code. Without the body, the processor can’t know how much space to reserve.

To define a class in an object-oriented language , we implement its methods and specify its attributes. Similar goes for any type in any language.

To define a variable in a statically typed language , we need to specify its type explicitly. However, that’s the same as declaring it. So, a statement can both declare and define an identifier in some cases.

For instance, int x from the above example creates an identifier named x , reserves the space for an integer in the memory, and links the identifier to it:

Defining a variable

Consequently, the linker knows where to find the value of x . But that doesn’t mean the variable will have any value when we try to use it. Further, how do we define variables in dynamically typed languages?

We solve those issues with initialization.

4. Initialization

To initialize a variable, we assign it its starting value. That way, we make sure the expressions using the variable won’t throw a runtime error.

In a statically typed language, initialization and definition can be separate steps but can happen at the same time. For example:

In dynamically typed languages, we define a variable by initializing it since there are no explicit type declarations:

Further, depending on the language rules or the code processor, each type can have a default value . That means that every variable in such a statically typed language will get its type’s default value when we define it. If that’s the case, initialization is implicit.

5. Conclusion

In this article, we talked about declarations, definitions, and initialization. They mean different things but sometimes overlap in code.

XWikiGuest

  • Developer Help
  • What's New

C Programming Variable Declarations and Definitions

In the C programming language, variables must be declared before they can be used. This tells the compiler how to work with the variable and tells the linker how much space needs to be allocated for it.

  • Variable Declarations

To declare a variable, you need to provide its  type  and an  identifier  (name). The general form for declaring variables is:

type identifier 1 ,  identifier 2 , …  identifier n ;

This means you can declare one or more variables of the same type by starting with the type, followed by a comma-separated list of identifiers with a semicolon at the very end. Variables of the same type don't need to be declared together. You could also split them up into multiple declarations of a single variable, each on its own line. In fact, this is a more common practice as it makes it easier to add a comment after each variable to describe its purpose.

Here are a few examples of variable declarations:

  • Variable Declarations with Definitions

Sometimes, you will want to ensure that a variable has an initial value for its first use. Conveniently, this can be done as part of the variable's declaration. The general form to both declare and define a variable in one step looks like this:

  type identifier 1  =  value 1 ,  identifier 2  =  value 2 , …  identifier n  =  value n ;

While initializing variables like this can be very convenient, there is a price to pay in terms of startup time. The  C Runtime Environment  startup code initializes these variables before your  main()  function is called. The initial values are stored along with the program code in the non-volatile flash memory. When the device powers on, the startup code will loop through all the initialized variables and copy their initial values from Flash into the variable's RAM location.

Here are a few examples showing the various ways variables can be declared alone or declared and defined together:

c declaration vs assignment

On This Page

Microchip support.

Query Microchip Forums and get your questions answered by our community:

    Microchip Forums   AVR Freaks Forums

If you need to work with Microchip Support staff directly, you can submit a technical support case. Keep in mind that many questions can be answered through our self-help resources, so this may not be your speediest option.

    Technical Support Portal

  • Declaration of Variables

Variables are the basic unit of storage in a programming language . These variables consist of a data type, the variable name, and the value to be assigned to the variable. Unless and until the variables are declared and initialized, they cannot be used in the program. Let us learn more about the Declaration and Initialization of Variables in this article below.

What is Declaration and Initialization?

  • Declaration of a variable in a computer programming language is a statement used to specify the variable name and its data type. Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it.
  • Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable. If the value is not assigned to the Variable, then the process is only called a Declaration.

Basic Syntax

The basic form of declaring a variable is:

            type identifier [= value] [, identifier [= value]]…];

                                                OR

            data_type variable_name = value;

type = Data type of the variable

identifier = Variable name

value = Data to be stored in the variable (Optional field)

Note 1: The Data type and the Value used to store in the Variable must match.

Note 2: All declaration statements must end with a semi-colon (;)

Browse more Topics Under Data Types, Variables and Constants

  • Concept of Data types
  • Built-in Data Types
  • Constants in Programing Language 
  • Access Modifier
  • Variables of Built-in-Datatypes
  • Assignment Statement
  • Type Modifier

Rules to Declare and Initialize Variables

There are few conventions needed to be followed while declaring and assigning values to the Variables –

  • Variable names must begin with a letter, underscore, non-number character. Each language has its own conventions.
  • Few programming languages like PHP, Python, Perl, etc. do not require to specify data type at the start.
  • Always use the ‘=’ sign to initialize a value to the Variable.
  • Do not use a comma with numbers.
  • Once a data type is defined for the variable, then only that type of data can be stored in it. For example, if a variable is declared as Int, then it can only store integer values.
  • A variable name once defined can only be used once in the program. You cannot define it again to store another type of value.
  • If another value is assigned to the variable which already has a value assigned to it before, then the previous value will be overwritten by the new value.

Types of Initialization

Static initialization –.

In this method, the variable is assigned a value in advance. Here, the values are assigned in the declaration statement. Static Initialization is also known as Explicit Initialization.

Dynamic Initialization –

In this method, the variable is assigned a value at the run-time. The value is either assigned by the function in the program or by the user at the time of running the program. The value of these variables can be altered every time the program runs. Dynamic Initialization is also known as Implicit Initialization.

In C programming language –

In Java Programming Language –

FAQs on Declaration of Variables

Q1. Is the following statement a declaration or definition?

extern int i;

  • Declaration

Answer – Option B

Q2. Which declaration is correct?

  • int length;
  • float double;
  • float long;

Answer – Option A, double, long and int are all keywords used for declaration and keywords cannot be used for declaring a variable name.

Q3. Which statement is correct for a chained assignment?

  • int x, y = 10;
  • int x = y = 10;
  • Both B and C

Answer – Option C

Customize your course in 30 seconds

Which class are you in.

tutor

Data Types, Variables and Constants

  • Variables in Programming Language
  • Concept of Data Types
  • Type Modifiers
  • Access Modifiers
  • Constants in Programming Language

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Download the App

Google Play

Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues ) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

  The basics of storing a value.
  Expressions into which a value can be stored.
  Shorthand for changing an lvalue’s contents.
  Shorthand for incrementing and decrementing an lvalue’s contents.
  Accessing then incrementing or decrementing.
  How to avoid ambiguity.
  Write assignments as separate statements.

Practical C Programming, 3rd Edition by Steve Oualline

Get full access to Practical C Programming, 3rd Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 4. Basic Declarations and Expressions

A journey of a thousand miles must begin with a single step.

If carpenters made buildings the way programmers make programs, the first woodpecker to come along would destroy all of civilization.

Elements of a Program

If you are going to construct a building, you need two things: the bricks and a blueprint that tells you how to put them together. In computer programming, you need two things: data (variables) and instructions (code or functions). Variables are the basic building blocks of a program. Instructions tell the computer what to do with the variables.

Comments are used to describe the variables and instructions. They are notes by the author documenting the program so that the program is clear and easy to read. Comments are ignored by the computer.

In construction, before we can start, we must order our materials: “We need 500 large bricks, 80 half-size bricks, and 4 flagstones.” Similarly, in C, we must declare our variables before we can use them. We must name each one of our “bricks” and tell C what type of brick to use.

After our variables are defined, we can begin to use them. In construction, the basic structure is a room. By combining many rooms, we form a building. In C, the basic structure is a function. Functions can be combined to form a program.

An apprentice builder does not start out building the Empire State Building, but rather starts on a one-room house. In this chapter, we will concentrate on constructing simple one-function programs.

Basic Program Structure

The basic elements of a program are the data declarations, functions, and comments. Let’s see how these can be organized into a simple C program.

The basic structure of a one-function program is:

Heading comments tell the programmer about the program, and data declarations describe the data that the program is going to use.

Our single function is named main . The name main is special, because it is the first function called. Other functions are called directly or indirectly from main . The function main begins with:

and ends with:

The line return(0); is used to tell the operating system (UNIX or MS-DOS/Windows) that the program exited normally (Status=0). A nonzero status indicates an error—the bigger the return value, the more severe the error. Typically, a status of 1 is used for the most simple errors, like a missing file or bad command-line syntax.

Now, let’s take a look at our Hello World program ( Example 3-1 ).

At the beginning of the program is a comment box enclosed in /* and */ . Following this box is the line:

This statement signals C that we are going to use the standard I/O package. The statement is a type of data declaration. [ 5 ] Later we use the function printf from this package.

Our main routine contains the instruction:

This line is an executable statement instructing C to print the message “Hello World” on the screen. C uses a semicolon ( ; ) to end a statement in much the same way we use a period to end a sentence. Unlike line-oriented languages such as BASIC, an end-of-line does not end a statement. The sentences in this book can span several lines—the end of a line is treated just like space between words. C works the same way. A single statement can span several lines. Similarly, you can put several sentences on the same line, just as you can put several C statements on the same line. However, most of the time your program is more readable if each statement starts on a separate line.

The standard function printf is used to output our message. A library routine is a C procedure or function that has been written and put into a library or collection of useful functions. Such routines perform sorting, input, output, mathematical functions, and file manipulation. See your C reference manual for a complete list of library functions.

Hello World is one of the simplest C programs. It contains no computations; it merely sends a single message to the screen. It is a starting point. After you have mastered this simple program, you have done a number of things correctly.

Simple Expressions

Computers can do more than just print strings—they can also perform calculations. Expressions are used to specify simple computations. The five simple operators in C are listed in Table 4-1 .

Operator

Meaning

*

Multiply

/

Divide

+

Add

-

Subtract

%

Modulus (return the remainder after division)

Multiply ( * ), divide ( / ), and modulus ( % ) have precedence over add ( + ) and subtract (-). Parentheses, ( ), may be used to group terms. Thus:

yields 12, while:

Example 4-1 computes the value of the expression (1 + 2) * 4 .

Although we calculate the answer, we don’t do anything with it. (This program will generate a “null effect” warning to indicate that there is a correctly written, but useless, statement in the program.)

Think about how confused a workman would be if we were constructing a building and said,

“Take your wheelbarrow and go back and forth between the truck and the building site.” “Do you want me to carry bricks in it?” “No. Just go back and forth.”

We need to store the results of our calculations.

Variables and Storage

C allows us to store values in variables . Each variable is identified by a variable name .

In addition, each variable has a variable type . The type tells C how the variable is going to be used and what kind of numbers (real, integer) it can hold. Names start with a letter or underscore ( _ ), followed by any number of letters, digits, or underscores. Uppercase is different from lowercase, so the names sam , Sam , and SAM specify three different variables. However, to avoid confusion, you should use different names for variables and not depend on case differences.

Nothing prevents you from creating a name beginning with an underscore; however, such names are usually reserved for internal and system names.

Most C programmers use all-lowercase variable names. Some names like int , while , for , and float have a special meaning to C and are considered reserved words . They cannot be used for variable names.

The following is an example of some variable names:

The following are not variable names:

Avoid variable names that are similar. For example, the following illustrates a poor choice of variable names:

A much better set of names is:

Variable Declarations

Before you can use a variable in C, it must be defined in a declaration statement .

A variable declaration serves three purposes:

It defines the name of the variable.

It defines the type of the variable (integer, real, character, etc.).

It gives the programmer a description of the variable. The declaration of a variable answer can be:

The keyword int tells C that this variable contains an integer value. (Integers are defined below.) The variable name is answer . The semicolon ( ; ) marks the end of the statement, and the comment is used to define this variable for the programmer. (The requirement that every C variable declaration be commented is a style rule. C will allow you to omit the comment. Any experienced teacher, manager, or lead engineer will not.)

The general form of a variable declaration is:

where type is one of the C variable types ( int , float , etc.) and name is any valid variable name. This declaration explains what the variable is and what it will be used for. (In Chapter 9 , we will see how local variables can be declared elsewhere.)

Variable declarations appear just before the main() line at the top of a program.

One variable type is integer. Integer numbers have no fractional part or decimal point. Numbers such as 1, 87, and -222 are integers. The number 8.3 is not an integer because it contains a decimal point. The general form of an integer declaration is:

A calculator with an 8-digit display can only handle numbers between 99999999 and -99999999. If you try to add 1 to 99999999, you will get an overflow error. Computers have similar limits. The limits on integers are implementation dependent, meaning they change from computer to computer.

Calculators use decimal digits (0-9). Computers use binary digits (0-1) called bits. Eight bits make a byte. The number of bits used to hold an integer varies from machine to machine. Numbers are converted from binary to decimal for printing.

On most UNIX machines, integers are 32 bits (4 bytes), providing a range of 2147483647 (2 31 -1) to -2147483648. On the PC, most compilers use only 16 bits (2 bytes), so the range is 32767 (2 15 -1) to -32768. These sizes are typical. The standard header file limits.h defines constants for the various numerical limits. (See Chapter 18 , for more information on header files.)

The C standard does not specify the actual size of numbers. Programs that depend on an integer being a specific size (say 32 bits) frequently fail when moved to another machine.

Question 4-1 : The following will work on a UNIX machine, but will fail on a PC :

Why does this fail? What will be the result when it is run on a PC? (Click here for the answer Section 4.12 )

Assignment Statements

Variables are given a value through the use of assignment statements. For example:

is an assignment. The variable answer on the left side of the equal sign ( = ) is assigned the value of the expression (1 + 2) * 4 on the right side. The semicolon ( ; ) ends the statement.

Declarations create space for variables. Figure 4-1 A illustrates a variable declaration for the variable answer . We have not yet assigned it a value so it is known as an uninitialized variable . The question mark indicates that the value of this variable is unknown.

Assignment statements are used to give a variable a value. For example:

is an assignment. The variable answer on the left side of the equals operator ( = ) is assigned the value of the expression (1 + 2) * 4 . So the variable answer gets the value 12 as illustrated in Figure 4-1 B.

The general form of the assignment statement is:

The = is used for assignment. It literally means: Compute the expression and assign the value of that expression to the variable. (In some other languages, such as PASCAL, the = operator is used to test for equality. In C, the operator is used for assignment.)

In Example 4-2 , we use the variable term to store an integer value that is used in two later expressions.

A problem exists with this program. How can we tell if it is working or not? We need some way of printing the answers.

printf Function

The library function printf can be used to print the results. If we add the statement:

the program will print:

The special characters %d are called the integer conversion specification . When printf encounters a %d , it prints the value of the next expression in the list following the format string. This is called the parameter list .

The general form of the printf statement is:

where format is the string describing what to print. Everything inside this string is printed verbatim except for the %d conversions. The value of expression-1 is printed in place of the first %d , expression-2 is printed in place of the second, and so on.

Figure 4-2 shows how the elements of the printf statement work together to generate the final result.

The format string "Twice %d is %d\n" tells printf to display Twice followed by a space, the value of the first expression, then a space followed by is and a space, the value of the second expression, finishing with an end-of-line (indicated by \n ).

Example 4-3 shows a program that computes term and prints it via two printf functions.

The number of %d conversions in the format should exactly match the number of expressions in the printf . C will not verify this. (Actually, the GNU gcc compiler will check printf arguments, if you turn on the proper warnings.) If too many expressions are supplied, the extra ones will be ignored. If there are not enough expressions, C will generate strange numbers for the missing expressions.

Floating Point

Because of the way they are stored internally, real numbers are also known as floating-point numbers. The numbers 5.5, 8.3, and -12.6 are all floating-point numbers. C uses the decimal point to distinguish between floating-point numbers and integers. So 5.0 is a floating-point number, while 5 is an integer. Floating-point numbers must contain a decimal point. Floating-point numbers include: 3.14159, 0.5, 1.0, and 8.88.

Although you could omit digits before the decimal point and specify a number as .5 instead of 0.5, the extra clearly indicates that you are using a floating-point number. A similar rule applies to 12. versus 12.0. A floating-point zero should be written as 0.0.

Additionally, the number may include an exponent specification of the form:

For example, 1.2e34 is a shorthand version of 1.2 x 10 34 .

The form of a floating-point declaration is:

Again, there is a limit on the range of floating-point numbers that the computer can handle. This limit varies widely from computer to computer. Floating-point accuracy will be discussed further in Chapter 16 .

When a floating-point number using printf is written , the %f conversion is used. To print the expression 1.0/3.0 , we use this statement:

Floating Point Versus Integer Divide

The division operator is special. There is a vast difference between an integer divide and a floating-point divide. In an integer divide, the result is truncated (any fractional part is discarded). So the value of 19/10 is 1.

If either the divisor or the dividend is a floating-point number, a floating-point divide is executed. So 19.0/10.0 is 1.9. (19/10.0 and 19.0/10 are also floating-point divides; however, 19.0/10.0 is preferred for clarity.) Several examples appear in Table 4-2 .

Expression

Result

Result type

1 + 2

3

Integer

1.0 + 2.0

3.0

Floating Point

19 / 10

1

Integer

19.0 / 10.0

1.9

Floating Point

C allows the assignment of an integer expression to a floating-point variable. C will automatically perform the conversion from integer to floating point. A similar conversion is performed when a floating-point number is assigned to an integer. For example:

Notice that the expression 1 / 2 is an integer expression resulting in an integer divide and an integer result of 0.

Question 4-2 : Why is the result of Example 4-4 0.0”? What must be done to this program to fix it? (Click here for the answer Section 4.12 )

Question 4-3 : Why does 2 + 2 = 5928? (Your results may vary. See Example 4-5 .) (Click here for the answer Section 4.12 )

Question 4-4 : Why is an incorrect result printed? (See Example 4-6 .) (Click here for the answer Section 4.12 )

The type char represents single characters. The form of a character declaration is:

Characters are enclosed in single quotes ( ' ). 'A' , 'a' , and '!' are character constants. The backslash character (\) is called the escape character . It is used to signal that a special character follows. For example, the characters \ " can be used to put a double quote inside a string. A single quote is represented by \' . \n is the newline character. It causes the output device to go to the beginning of the next line (similar to a return key on a typewriter). The characters \\ are the backslash itself. Finally, characters can be specified by \ nnn , where nnn is the octal code for the character. Table 4-3 summarizes these special characters. Appendix A contains a table of ASCII character codes.

Character

Name

Meaning

Backspace

Move the cursor to the left by one character

Form Feed

Go to top of new page

Newline

Go to next line

Return

Go to beginning of current line

Tab

Advance to next tab stop (eight column boundary)

Apostrophe

Character '

Double quote

Character

Backslash

Character

 

Character number (octal)

While characters are enclosed in single quotes ( ' ), a different data type, the string, is enclosed in double quotes ( " ). A good way to remember the difference between these two types of quotes is to remember that single characters are enclosed in single quotes. Strings can have any number of characters (including one), and they are enclosed in double quotes.

Characters use the printf conversion %c . Example 4-7 reverses three characters.

When executed, this program prints:

Answer 4-1 : The largest number that can be stored in an int on most UNIX machines is 2147483647. When using Turbo C++, the limit is 32767. The zip code 92126 is larger than 32767, so it is mangled, and the result is 26590.

This problem can be fixed by using a long int instead of just an int . The various types of integers will be discussed in Chapter 5 .

Answer 4-2 : The problem concerns the division: 1/3 . The number 1 and the number 3 are both integers, so this question is an integer divide. Fractions are truncated in an integer divide. The expression should be written as:

Answer 4-3 : The printf statement:

tells the program to print a decimal number, but there is no variable specified. C does not check to make sure printf is given the right number of parameters. Because no value was specified, C makes one up. The proper printf statement should be:

Answer 4-4 : The problem is that in the printf statement, we used a %d to specify that an integer was to be printed, but the parameter for this conversion was a floating-point number. The printf function has no way of checking its parameters for type. So if you give the function a floating-point number, but the format specifies an integer, the function will treat the number as an integer and print unexpected results.

Programming Exercises

Exercise 4-1 : Write a program to print your name, social security number, and date of birth.

Exercise 4-2 : Write a program to print a block E using asterisks ( * ), where the E has a height of seven characters and a width of five characters.

Exercise 4-3 : Write a program to compute the area and perimeter of a rectangle with a width of three inches and a height of five inches. What changes must be made to the program so that it works for a rectangle with a width of 6.8 inches and a length of 2.3 inches?

Exercise 4-4 : Write a program to print “HELLO” in big block letters; each letter should have a height of seven characters and width of five characters.

Exercise 4-5 : Write a program that deliberately makes the following mistakes:

Prints a floating-point number using the %d conversion.

Prints an integer using the %f conversion.

Prints a character using the %d conversion.

[ 5 ] Technically, the statement causes a set of data declarations to be taken from an include file. Chapter 10 , discusses include files.

Get Practical C Programming, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

c declaration vs assignment

c declaration vs assignment




Tutorials








Practice




Resources







References




In C and C++, there is a subtle but important distinction between the meaning of the words declare and define. If you don't understand the difference, you'll run into weird linker errors like "undefined symbol foo" or "undefined reference to 'foo'" or even "undefined reference to vtable for foo" (in C++).

When you declare a variable, a function, or even a class all you are doing is saying: there is something with this name, and it has this type. The compiler can then handle most (but not all) uses of that name without needing the full definition of that name. Declaring a value--without defining it--allows you to write code that the compiler can understand without having to put all of the details. This is particularly useful if you are working with multiple source files, and you need to use a function in multiple files. You don't want to put the body of the function in multiple files, but you do need to provide a declaration for it.

So what does a declaration look like? For example, if you write:

This is a function declaration; it does not provide the body of the function, but it does tell the compiler that it can use this function and expect that it will be defined somewhere.

Defining something means providing all of the necessary information to create that thing in its entirety. Defining a function means providing a function body; defining a class means giving all of the methods of the class and the fields. Once something is defined, that also counts as declaring it; so you can often both declare and define a function, class or variable at the same time. But you don't have to.

For example, having a declaration is often good enough for the compiler. You can write code like this:

Since the compiler knows the return value of func, and the number of arguments it takes, it can compile the call to func even though it doesn't yet have the definition. In fact, the definition of the method func could go into another file!

You can also declare a class without defining it

Code that needs to know the details of what is in MyClass can't work--you can't do this:

Because the compiler needs to know the size of the variable an_object, and it can't do that from the declaration of MyClass; it needs the definition that shows up below.

Most of the time, when you declare a variable, you are also providing the definition. What does it mean to define a variable, exactly? It means you are telling the compiler where to create the storage for that variable. For example, if you write:

The line int x; both declares and defines the variable; it effectively says, "create a variable named x, of type int. Also, the storage for the variable is that it is a global variable defined in the object file associated with this source file." That's kind of weird, isn't it? What is going on is that someone else could actually write a second source file that has this code:

Now the use of is creating a declaration of a variable but NOT defining it; it is saying that the storage for the variable is somewhere else. Technically, you could even write code like this:

And now you have a declaration of x at the top of the program and a definition at the bottom. But usually extern is used when you want to access a global variable declared in another source file, as I showed above, and then link the two resulting object files together after compilation. Using extern to declare a global variable is pretty much the same thing as using a function declaration to declare a function in a header file. (In fact, you'd generally put extern in a header file rather than putting it in a source file.)

In fact, if you put a variable into a header file and do not use extern, you will run into the inverse problem of an undefined symbol; you will have a symbol with multiple definitions, with an error like "redefinition of 'foo'". This will happen when the linker goes to link together multiple object files.

A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols.

If you want to use a function across multiple source files, you should declare the function in one header file (.h) and then put the function definition in one source file (.c or .cpp). All code that uses the function should include just the .h file, and you should link the resulting object files with the object file from compiling the source file.

If you want to use a class in multiple files, you should put the class definition in a header file and define the class methods in a corresponding source file. (You an also use for the methods.)

If you want to use a variable in multiple files, you should put the declaration of the variable using the extern keyword in one header file, and then include that header file in all source files that need that variable. Then you should put the definition of that variable in one source file that is linked with all the object files that use that variable.




A brief description of the compiling and linking process

can help you avoid the problem of having multiple declarations for the same name

Compiler warnings are meaningful--learn how and why to deal with them

| | | |

1.4 — Variable assignment and initialization

  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture

Difference between Definition and Declaration

In programming, the distinction between definition and declaration constitutes the basic concepts required while writing programs and managing the code. Declarations and definitions are employed to describe more about the variables, functions, or types to the compiler or interpreter for a program. A declaration is a way of informing the program about the name and type of an entity, it will handle. A definition on the other hand initiates storage or defines where the implementation of the entity can be gotten from. It is important to distinguish between these concepts to structure code and control its scope as well as determine how different units have to be linked as a project grows in complexity.

What is a Declaration?

Declaration of a variable is for informing the compiler of the following information: name of the variable and the type of the value it will hold i.e., declaration gives details about the properties of a variable. Whereas, in the Definition of a variable, memory is allocated for the variable.

In C language definition and declaration for a variable takes place at the same time. i.e. there is no difference between declaration and definition. For example, consider the following statement,

Here, the information such as the variable name: a, and data type : int, is sent to the compiler which will be stored in the data structure known as the symbol table. Along with this, a memory of size 4 bytes(depending upon the type of compiler) will be allocated. Suppose, if we want to only declare variables and not define them i.e. we do not want to allocate memory, then the following declaration can be used

In this example, only the information about the variable name and type is sent and no memory allocation is done. The above information tells the compiler that the variable a is declared now while memory for it will be defined later in the same file or in a different file.

What is Definition?

Declaration of a function provides the compiler with the name of the function , the number and type of arguments it takes, and its return type. For example, consider the following code,

Here, a function named add is declared with 2 arguments of type int and return type int. Memory will not be allocated at this stage.

Definition of the function is used for allocating memory for the function. For example, consider the following function definition,

During this function definition , the memory for the function add will be allocated. A variable or a function can be declared any number of times but, it can be defined only once.

Difference Between Definition and Declaration

Parameters

Definition

Declaration

Purpose

Allocates memory and initializes a variable/function.

Specifies the name and type of a variable/function.

Memory Allocation

Allocates memory.

Does not allocate memory.

Initialization

Can include initialization.

Does not include initialization.

Usage

Used to create and initialize an entity.

Used to inform the compiler about an entity.

Scope

Creates an entity in a specific scope.

Provides information about an entity’s type.

Function Context

Includes function body for functions.

Includes function signature without the body.

Multiple Occurrences

Can only occur once for a variable/function in a file.

Can occur multiple times in a file.

Compilation Phase

Happens in the compilation phase where memory is allocated.

Happens during the syntax checking phase.

Linking

Used by the linker to resolve references.

Informs the compiler about the existence of a variable/function.

Header Files

Not typically included in header files.

Commonly included in header files.

Syntax Requirement

Must follow the complete syntax for variable initialization or function implementation.

Only requires the type and name for variables/functions.

Visibility

Makes the variable/function visible and usable.

Makes the variable/function known to the compiler, but not usable without definition.

In conclusion, understanding and implementing definitions and declarations in programs is important for any programmer. The declaration makes an entity known to the compiler and also the kind of entity it is so that the compiler can locate any instance of it in the code. Hence a definition goes further in that it assigns memory or gives the implementation of that entity. It makes understanding how code should be organized, how dependencies have to be managed and where types, their instances and their linkages should be kept and recalled important for constructing scalable and maintainable software systems.

Frequently Asked Questions on Definition and Declaration – FAQs

Is it possible to declare a variable or function multiple times.

Yes, it is legal to have a variable or a function declared using the same name in the same scope. However, it can only be defined once, which means that it causes redefinition errors when it is used in the next block.

Where are definitions and declarations typically placed in a program?

Definitions are commonly associated with source files in which memory allocation and initialization of the respective objects take place, whereas declarations are usually introduced in the header files to be reused in several source files.

Do definitions and declarations affect the compilation process differently?

Yes, definitions influence the compilation process in a way that it allocates memory to the variables and also Initialized the variables, on the other side declaration helps the compiler to check syntax as well as whether the type and name must be correct or not.

Can a declaration be used without a definition?

No, you cannot use a declaration without a definition to go with it. The definition is involved as it helps in assigning memory space and initial value to the variable or contains the function’s code.

What happens if you declare a function but do not define it?

If a function is declared but not defined, the linker will go and produce an error and this is because the implementation part of this function cannot be found by the linker at the linking stage.

Similar Reads

  • Computer Subject

Please Login to comment...

  • Free Music Recording Software in 2024: Top Picks for Windows, Mac, and Linux
  • Best Free Music Maker Software in 2024
  • What is Quantum AI? The Future of Computing and Artificial Intelligence Explained
  • Noel Tata: Ratan Tata's Brother Named as a new Chairman of Tata Trusts
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Search anything:

Definition vs Declaration vs Initialization in C/ C++

C++ c programming software engineering.

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

In this article, we have covered the differences between 3 core terms Definition, Declaration and Initialization in C and C++ along with code snippets.

Table of contents:

  • Declaration
  • Initialization

Conclusion / Table of Differences

To understand the difference between the two we should first understand each term independently.So,here we go.

1. Declaration

Declaration of a variable is generally a introduction to a new memory allocated to something that we may call with some name.

Properties of declaration - 1.Memory creation occurs at the time of declaration itself. 2.Variables may have garbage values. 3.Variables cannot be used before declaration.

2. Definition

In declaration, user defines the previously declared variable.

3. Initialisation

Initialisation is nothing but assigning the value at the time of declaration.

From the above explanation we can conclude the following-

  • Declaration is just naming the variable.
  • Definition does not means declaration '+' Initialisation as definition might be without initialisation.
  • Initialisation is assigning valueto the declared variable. (At the time of declaration)
Declaration Definition Initialisation
1.Declaration is just naming the variable. Definition is declarartion without intialisation. initialisation is declaration with definition at thesame time.
2.Variables may have garbage values Variables may or may not have garbage values Variables do not have garbage values
3 Declaration can be done any number of times. Definition done only once Initialisation done only once
4.Memory will not be allocated during declaration Memory will be allocated during definition Memory will be allocated during initialisation
5.Declaration provides basic attributes of a variable/function. definition provides details of that variable/function. Initialisation provides details of that variable/function and value.

With this article at OpenGenus, you must have the complete idea of Definition vs Declaration vs Initialization in C/ C++.

OpenGenus IQ: Learn Algorithms, DL, System Design icon

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Declarations and definitions (C++)

  • 8 contributors

A C++ program consists of various entities such as variables, functions, types, and namespaces. Each of these entities must be declared before they can be used. A declaration specifies a unique name for the entity, along with information about its type and other characteristics. In C++ the point at which a name is declared is the point at which it becomes visible to the compiler. You can't refer to a function or class that is declared at some later point in the compilation unit. Variables should be declared as close as possible before the point at which they're used.

The following example shows some declarations:

On line 5, the main function is declared. On line 7, a const variable named pi is declared and initialized . On line 8, an integer i is declared and initialized with the value produced by the function f . The name f is visible to the compiler because of the forward declaration on line 3.

In line 9, a variable named obj of type C is declared. However, this declaration raises an error because C isn't declared until later in the program, and isn't forward-declared. To fix the error, you can either move the entire definition of C before main or else add a forward-declaration for it. This behavior is different from other languages such as C#. In those languages, functions and classes can be used before their point of declaration in a source file.

In line 10, a variable named str of type std::string is declared. The name std::string is visible because it's introduced in the string header file , which is merged into the source file in line 1. std is the namespace in which the string class is declared.

In line 11, an error is raised because the name j hasn't been declared. A declaration must provide a type, unlike other languages such as JavaScript. In line 12, the auto keyword is used, which tells the compiler to infer the type of k based on the value that it's initialized with. The compiler in this case chooses int for the type.

Declaration scope

The name that is introduced by a declaration is valid within the scope where the declaration occurs. In the previous example, the variables that are declared inside the main function are local variables . You could declare another variable named i outside of main, at global scope , and it would be a separate entity. However, such duplication of names can lead to programmer confusion and errors, and should be avoided. In line 21, the class C is declared in the scope of the namespace N . The use of namespaces helps to avoid name collisions . Most C++ Standard Library names are declared within the std namespace. For more information about how scope rules interact with declarations, see Scope .

Definitions

Some entities, including functions, classes, enums, and constant variables, must be defined as well as declared. A definition provides the compiler with all the information it needs to generate machine code when the entity is used later in the program. In the previous example, line 3 contains a declaration for the function f but the definition for the function is provided in lines 15 through 18. On line 21, the class C is both declared and defined (although as defined the class doesn't do anything). A constant variable must be defined, in other words assigned a value, in the same statement in which it's declared. A declaration of a built-in type such as int is automatically a definition because the compiler knows how much space to allocate for it.

The following example shows declarations that are also definitions:

Here are some declarations that aren't definitions:

Typedefs and using statements

In older versions of C++, the typedef keyword is used to declare a new name that is an alias for another name. For example, the type std::string is another name for std::basic_string<char> . It should be obvious why programmers use the typedef name and not the actual name. In modern C++, the using keyword is preferred over typedef , but the idea is the same: a new name is declared for an entity, which is already declared and defined.

Static class members

Static class data members are discrete variables that are shared by all objects of the class. Because they're shared, they must be defined and initialized outside the class definition. For more information, see Classes .

extern declarations

A C++ program might contain more than one compilation unit . To declare an entity that's defined in a separate compilation unit, use the extern keyword. The information in the declaration is sufficient for the compiler. However, if the definition of the entity can't be found in the linking step, then the linker will raise an error.

In this section

Storage classes const constexpr extern Initializers Aliases and typedefs using declaration volatile decltype Attributes in C++

Basic Concepts

Was this page helpful?

Additional resources

cppreference.com

Declarations.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
(C++26)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
Specifiers
function specifier
function specifier
(C++20)
/struct
volatile
(C++26)    
(C++11)
Declarators
Block declarations
(C++17)
(C++11)
declaration
directive
declaration (C++11)
declaration
(C++11)
Other declarations
(C++11)
(C++11)

Declarations are how names are introduced (or re-introduced) into the C++ program. Not all declarations actually declare anything, and each kind of entity is declared differently. Definitions are declarations that are sufficient to use the entity identified by the name.

A declaration is one of the following:

  • Function definition
  • Template declaration (including Partial template specialization )
  • Explicit template instantiation
  • Explicit template specialization
  • Namespace definition
  • Linkage specification
) (since C++11)
  • Empty declaration ( ; )
  • A function declaration without a decl-specifier-seq  :
attr (optional) declarator
attr - (since C++11) sequence of any number of
declarator - a function declarator
  • block-declaration (a declaration that can appear inside a block ), which, in turn, can be one of the following:
  • asm declaration
(since C++11)
  • namespace alias definition
  • using-declaration
  • using directive
(since C++20)
declaration (since C++11)
  • simple declaration
Simple declaration Specifiers Declarators Notes Example Defect reports See also

[ edit ] Simple declaration

A simple declaration is a statement that introduces, creates, and optionally initializes one or several identifiers, typically variables.

decl-specifier-seq init-declarator-list (optional) (1)
attr decl-specifier-seq init-declarator-list (2)
attr - (since C++11) sequence of any number of
decl-specifier-seq - sequence of (see below)
init-declarator-list - comma-separated list of with optional . init-declarator-list is optional when declaring a named class/struct/union or a named enumeration

A structured binding declaration is also a simple declaration. (since C++17)

[ edit ] Specifiers

Declaration specifiers ( decl-specifier-seq ) is a sequence of the following whitespace-separated specifiers, in any order:

  • the typedef specifier. If present, the entire declaration is a typedef declaration and each declarator introduces a new type name, not an object or a function.
  • function specifiers ( inline , virtual , explicit ), only allowed in function declarations .
specifier is also allowed on variable declarations. (since C++17)
  • the friend specifier, allowed in class and function declarations.
specifier, only allowed in variable definitions, function and function template declarations, and the declaration of static data members of literal type. (since C++11)
specifier, only allowed in function and function template declarations. specifier, only allowed in declaration of a variable with static or thread storage duration. At most one of the constexpr, consteval, and constinit specifiers is allowed to appear in a decl-specifier-seq. (since C++20)
  • storage class specifier ( register , (until C++17) static , thread_local , (since C++11) extern , mutable ). Only one storage class specifier is allowed , except that thread_local may appear together with extern or static (since C++11) .
  • Type specifiers ( type-specifier-seq ), a sequence of specifiers that names a type. The type of every entity introduced by the declaration is this type, optionally modified by the declarator (see below). This sequence of specifiers is also used by type-id . Only the following specifiers are part of type-specifier-seq , in any order:
  • class specifier
  • enum specifier
  • simple type specifier
  • char , char8_t , (since C++20) char16_t , char32_t , (since C++11) wchar_t , bool , short , int , long , signed , unsigned , float , double , void
(since C++11)
(since C++26)
  • previously declared class name (optionally qualified )
  • previously declared enum name (optionally qualified )
  • previously declared typedef-name or type alias (since C++11) (optionally qualified )
  • template name with template arguments (optionally qualified , optionally using template disambiguator )
): see (since C++17)
  • elaborated type specifier
  • the keyword class , struct , or union , followed by the identifier (optionally qualified ), previously defined as the name of a class.
  • the keyword class , struct , or union , followed by template name with template arguments (optionally qualified , optionally using template disambiguator ), previously defined as the name of a class template.
  • the keyword enum followed by the identifier (optionally qualified ), previously declared as the name of an enumeration.
  • typename specifier
  • cv qualifier
  • const can be combined with any type specifier except itself.
  • volatile can be combined with any type specifier except itself.
  • signed or unsigned can be combined with char , long , short , or int .
  • short or long can be combined with int .
  • long can be combined with double .
can be combined with long. (since C++11)

Attributes may appear in decl-specifier-seq , in which case they apply to the type determined by the preceding specifiers.

Repetitions of any specifier in a decl-specifier-seq , such as const static const , or virtual inline virtual are errors , except that long is allowed to appear twice (since C++11) .

[ edit ] Declarators

init-declarator-list is a comma-separated sequence of one or more init-declarators , which have the following syntax:

declarator initializer (optional) (1)
declarator requires-clause (2) (since C++20)
declarator - the declarator
initializer - optional initializer (except where required, such as when initializing references or const objects). See for details.
requires-clause - , which adds a to a

Each init-declarator in an init-declarator sequence S D1, D2, D3 ; is processed as if it were a standalone declaration with the same specifiers: S D1 ; S D2 ; S D3 ; .

Each declarator introduces exactly one object, reference, function, or (for typedef declarations) type alias, whose type is provided by decl-specifier-seq and optionally modified by operators such as & (reference to) or [ ] (array of) or ( ) (function returning) in the declarator. These operators can be applied recursively, as shown below.

A declarator is one of the following:

unqualified-id attr (optional) (1)
qualified-id attr (optional) (2)
identifier attr (optional) (3) (since C++11)
attr (optional) cv (optional) declarator (4)
nested-name-specifier attr (optional) cv (optional) declarator (5)
attr (optional) declarator (6)
attr (optional) declarator (7) (since C++11)
noptr-declarator constexpr (optional) attr (optional) (8)
noptr-declarator parameter-list cv (optional) ref  (optional) except (optional) attr (optional) (9)

In all cases, attr is an optional sequence of . When appearing immediately after the identifier, it applies to the object being declared.

(since C++11)

cv is a sequence of const and volatile qualifiers, where either qualifier may appear at most once in the sequence.

This section is incomplete
Reason: explain declaration name hiding rules; how a variable/function declaration hides a class (but not a typedef) with the same name

[ edit ] Notes

When a block-declaration appears inside a block , and an identifier introduced by a declaration was previously declared in an outer block, the outer declaration is hidden for the remainder of the block.

If a declaration introduces a variable with automatic storage duration, it is initialized when its declaration statement is executed. All automatic variables declared in a block are destroyed on exit from the block (regardless how the block is exited: via exception , goto , or by reaching its end), in order opposite to their order of initialization.

[ edit ] Example

Note: this example demonstrates how some complex declarations are parsed in terms of the language grammar. Other popular mnemonics are: the spiral rule , reading inside-out , and declaration mirrors use . There is also an automated parser at https://cdecl.org .

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++98 the declarators of redeclarations could not be qualified qualified declarators allowed
C++98 a single standalone semicolon was not a valid declaration it is an empty declaration,
which has no effect
C++98 repetition of a function specifier in a decl-specifier-seq was allowed repetition is forbidden

[ edit ] See also

for Declarations
  • Todo with reason
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 00:10.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Staging Ground badges

Earn badges by improving or asking questions in Staging Ground.

Meanings of declaring, instantiating, initializing and assigning an object

Technically what are the meanings and differences of the terms declaring , instantiating , initializing and assigning an object in C#?

I think I know the meaning of assigning but I have no formal definition.

In msdn, it is said "the act of creating an object is called instantiation". But the meaning creating seems vague to me. You can write

is a then created?

  • terminology

Minimus Heximus's user avatar

  • i have never seen clarifying . but instantiating means to create an instance of an object. initializing means setting value to an object.(does not necessarily create new instance). assigning is self descriptive. assign a value to an object. i maybe wrong. but thats what i think –  M.kazem Akhgary Commented Aug 29, 2015 at 21:42
  • FYI, int is a primitive type, not an object. –  OldProgrammer Commented Aug 29, 2015 at 21:45
  • sorry I meant declaring. –  Minimus Heximus Commented Aug 29, 2015 at 21:45
  • declaring is just what you have shown. like int a; you declared an int named a but you still not initialized it. –  M.kazem Akhgary Commented Aug 29, 2015 at 21:52
  • 1 instantiate is for class objects. means create a new object with new reference. for a=2 you say initialize. –  M.kazem Akhgary Commented Aug 29, 2015 at 21:57

2 Answers 2

Declaring - Declaring a variable means to introduce a new variable to the program. You define its type and its name.

Instantiate - Instantiating a class means to create a new instance of the class. Source .

Initialize - To initialize a variable means to assign it an initial value.

Assigning - Assigning to a variable means to provide the variable with a value.

Zarwan's user avatar

  • So Instantiation is not used for structs or simple types? –  Minimus Heximus Commented Aug 29, 2015 at 22:00
  • Can "initializing" mean "assigning for the first time after declaration"? –  Minimus Heximus Commented Aug 29, 2015 at 22:04
  • 1 The term is used for structs, although I am honestly not sure why. However "instantiate" is not used for simple types. And yes, that is basically the meaning of initialize. @MinimusHeximus –  Zarwan Commented Aug 29, 2015 at 22:10

In general:

Declare means to tell the compiler that something exists, so that space may be allocated for it. This is separate from defining or initializing something in that it does not necessarily say what "value" the thing has, only that it exists. In C/C++ there is a strong distinction between declaring and defining. In C# there is much less of a distinction, though the terms can still be used similarly.

Instantiate literally means "to create an instance of". In programming, this generally means to create an instance of an object (generally on "the heap"). This is done via the new keyword in most languages. ie: new object(); . Most of the time you will also save a reference to the object. ie: object myObject = new object(); .

Initialize means to give an initial value to. In some languages, if you don't initialize a variable it will have arbitrary (dirty/garbage) data in it. In C# it is actually a compile-time error to read from an uninitialized variable.

Assigning is simply the storing of one value to a variable. x = 5 assigns the value 5 to the variable x . In some languages, assignment cannot be combined with declaration, but in C# it can be: int x = 5; .

Note that the statement object myObject = new object(); combines all four of these.

  • new object() instantiates a new object object, returning a reference to it.
  • object myObject declares a new object reference.
  • = initializes the reference variable by assigning the value of the reference to it.

Dave Cousineau's user avatar

  • Do we have the term defining too? What defining means? –  Minimus Heximus Commented Aug 29, 2015 at 22:22
  • 1 @MinimusHeximus Define means give a value (or body) to. We don't really use "define" much in C#, but it would be similar in meaning to initialize. When you write a method, I guess you could call that defining the method, though it doesn't have any contrast with declaring the method like it would in C++. –  Dave Cousineau Commented Aug 29, 2015 at 22:35

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# terminology or ask your own question .

  • The Overflow Blog
  • Is this the real life? Training autonomous cars with simulations
  • What launching rockets taught this CTO about hardware observability
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Feedback Requested: How do you use the tagged questions page?
  • Proposed designs to update the homepage for logged-in users

Hot Network Questions

  • How should I handle students who are very disengaged in class?
  • Book about a homeless girl who volunteers at a shady facility for money
  • For non-native English speakers, is it ok to use ChatGPT as a translation assistant?
  • Reviewing a paper that's badly written such that reading it takes a long time
  • bind_rows on a list fails if some sub-list elements are empty. Why?
  • Expected number of cards that are larger than both of their neighbors
  • Horror / Thriller film with a mother and her baby surviving after a virus has turned people into zombie-like killers
  • Is it possible to build a Full-Spectrum White Laser?
  • How good is Quicken Spell as a feat?
  • Universal footprint for 16 bit ISA slot
  • How did Vladimir Arnold explain the difference in approaches between mathematicians and physicists?
  • Graduate Instance colour by constant interpolation
  • What challenge did Jesus put before the rich young man in Mtt19?
  • Why/how am I over counting here?
  • What happens in a game where one side has a minor piece and the other side has a rook or a pawn and is flagged on time?
  • Customize the man command's status prompt to show percentage read
  • Are there any sane ways to make or explore the properties of FOOF (dioxygen difluoride)?
  • Simple console calculator app. Looking for structure/best practices tips
  • Crocodile paradox
  • In what Disney film did a gelatinous cube appear?
  • How to reduce the precision of a shape without creating duplicated points?
  • Reference on why finding a feasible solution to the Set Partitioning problem is NP-Hard?
  • What is the difference between and Indefinite Adjectives and Indefinite Pronouns?
  • Generate random lon/lat coordinate anywhere on the map

c declaration vs assignment

IMAGES

  1. 4. Basic Declarations and Expressions

    c declaration vs assignment

  2. C Programming

    c declaration vs assignment

  3. 54 Declaration vs Assignment Intro

    c declaration vs assignment

  4. Difference Between Declaration And Definition Of A Variable

    c declaration vs assignment

  5. Variable Declaration and Initialization in C Language| Declaration vs Definition vs Initialization

    c declaration vs assignment

  6. PPT

    c declaration vs assignment

VIDEO

  1. Function Declaration VS Function Expression #shorts #javascript

  2. #12. Variable in C

  3. What is variable declaration || Variable Initialization and cout in C++ , Urdu/Hindi

  4. Declaration of Independence

  5. DECREE A THING! Declaration Vs Decree #prophetlovylelias #revelationchurch #revelationnation

  6. Prophet!c Declaration#apostlejoshuaselmannimmak #koinoniaglobal #church #Yeshuaworld #highlight

COMMENTS

  1. Difference between declaration statement and assignment statement in C

    Declaration: int a; Assignment: a = 3; Declaration and assignment in one statement: int a = 3; Declaration says, "I'm going to use a variable named "a" to store an integer value."Assignment says, "Put the value 3 into the variable a." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.

  2. What exactly are C++ definitions, declarations and assignments?

    A declaration tells the compiler, or programmer that the function or variable exists. e.g. An assignment is when a variable has its value set, usually with the = operator. e.g. Actually I would consider "int var;" to be definition, "int var = 5;" is a combined def/ass.

  3. Why declare a variable in one line, and assign to it in the next?

    Declaration and definition in C/C++ is not mutually exclusive concepts. Actually, definition is just a specific form of declaration. Every definition is a declaration at the same time (with few exceptions). ... If I have some types, names, and assignment all going on in the same tight space, it's a bit of information overload. Further, it means ...

  4. Explain the variable declaration, initialization and assignment in C

    Explain the variable declaration initialization and assignment in C language - The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution.The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.V

  5. Differences Between Definition, Declaration, and Initialization

    It depends on the language we're coding in and the thing we want to declare, define or initialize. 2. Declarations. A declaration introduces a new identifier into a program's namespace. The identifier can refer to a variable, a function, a type, a class, or any other construct the language at hand allows. For a statement to be a declaration ...

  6. C Programming Variable Declarations and Definitions

    C Programming Variable Declarations and Definitions. A variable declaration is when you specify a type and an identifier but have not yet assigned a value to the variable. A variable definition is when you assign a value to a variable, typically with the assignment operator =. In the C programming language, variables must be declared before ...

  7. Declarations

    A declaration is a C language construct that introduces one or more identifiers into the program and specifies their meaning and properties.. Declarations may appear in any scope. Each declaration ends with a semicolon (just like a statement) and consists of two (until C23) three (since C23) distinct parts:

  8. Declaration and Initialization of Variables: How to Declare ...

    The basic form of declaring a variable is: type identifier [= value] [, identifier [= value]]…]; OR. data_type variable_name = value; where, type = Data type of the variable. identifier = Variable name. value = Data to be stored in the variable (Optional field) Note 1: The Data type and the Value used to store in the Variable must match.

  9. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  10. 4. Basic Declarations and Expressions

    The keyword int tells C that this variable contains an integer value. (Integers are defined below.) The variable name is answer.The semicolon (;) marks the end of the statement, and the comment is used to define this variable for the programmer.(The requirement that every C variable declaration be commented is a style rule.

  11. Declare vs Define in C and C++

    A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to ...

  12. 1.4

    The process of specifying an initial value for an object is called initialization, and the syntax used to initialize an object is called an initializer. Informally, the initial value is often called an "initializer" as well. int width { 5 }; // define variable width and initialize with initial value 5 // variable width now has value 5.

  13. Difference between Definition and Declaration

    Declarations and definitions are employed to describe more about the variables, functions, or types to the compiler or interpreter for a program. A declaration is a way of informing the program about the name and type of an entity, it will handle. A definition on the other hand initiates storage or defines where the implementation of the entity ...

  14. Definition vs Declaration vs Initialization in C/ C++

    1.Declaration is just naming the variable. Definition is declarartion without intialisation. initialisation is declaration with definition at thesame time. 2.Variables may have garbage values. Variables may or may not have garbage values. Variables do not have garbage values. 3 Declaration can be done any number of times.

  15. Declarations and definitions (C++)

    Show 3 more. A C++ program consists of various entities such as variables, functions, types, and namespaces. Each of these entities must be declared before they can be used. A declaration specifies a unique name for the entity, along with information about its type and other characteristics. In C++ the point at which a name is declared is the ...

  16. Declarations

    A simple declaration is a statement that introduces, creates, and optionally initializes one or several identifiers, typically variables. decl-specifier-seqinit-declarator-list  (optional); (1) attrdecl-specifier-seqinit-declarator-list; (2) attr. -. (since C++11) sequence of any number of attributes.

  17. c++

    1. 4. Declaration is for the compiler to accept a name(to tell the compiler that the name is legal, the name is introduced with intention not a typo). Definition is where a name and its content is associated. The definition is used by the linker to link a name reference to the content of the name. - Gab是好人.

  18. Java: define terms initialization, declaration and assignment

    assignment: throwing away the old value of a variable and replacing it with a new one. initialization: it's a special kind of assignment: the first.Before initialization objects have null value and primitive types have default values such as 0 or false.Can be done in conjunction with declaration. declaration: a declaration states the type of a variable, along with its name.

  19. c#

    Declaring - Declaring a variable means to introduce a new variable to the program. You define its type and its name. int a; //a is declared. Instantiate - Instantiating a class means to create a new instance of the class. Source. MyObject x = new MyObject(); //we are making a new instance of the class MyObject.