• C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Compound Statements in C++
  • Rethrowing an Exception in C++
  • Variable Shadowing in C++
  • Condition Variables in C++ Multithreading
  • C++23 <print> Header
  • Literals In C++
  • How to Define Constants in C++?
  • C++ Variable Templates
  • Introduction to GUI Programming in C++
  • Concurrency in C++
  • Hybrid Inheritance In C++
  • Dereference Pointer in C
  • shared_ptr in C++
  • Nested Inline Namespaces In C++20
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++
  • Partial Template Specialization in C++
  • Address Operator & in C
  • Attendance Marking System in C++

Pass By Reference In C

Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program.

Pass By Reference in C

In this method, the address of an argument is passed to the function instead of the argument itself during the function call. Due to this, any changes made in the function will be reflected in the original arguments. We use the address operator (&) and indirection operator (*) to provide an argument to a function via reference.

When any argument is passed by reference in the function call as a parameter, it is passed using the address of(&) operator from the main function. In the function definition, the function takes the value of the parameter by using (*) operator . By using this, it can directly access the value of the parameter directly from its original location. There will be no need for extra memory or copying the same data into some other fields.

Also, a pointer type must be defined for the matching parameter in the called function in C.

The code will look like this in the pass-by-reference method:

Example of Pass by Reference

In the below program, the arguments that are passed by reference will be swapped with each other.

Explanation

In the above code, n1 and n2 are assigned by the values 5 and 10. When the swap function is called and the address of n1, and n2 are passed as a parameter to the function, then the changes made to the n1 and n2 in the swap function will also reflect in the main function. The swap function will directly access and change the values of n1, and n2 using their addresses. So, after execution of the swap function, the values of n1 and n2 are swapped.

Points to Remember

  • When calling a function by reference, the actual parameter is the address of the variable that is being called.
  • Since the address of the actual parameters is passed, the value of the actual parameters can be altered.
  • Changes performed inside the function remain valid outside of it. By altering the formal parameters , the values of the real parameters actually change.
  • Both actual and formal parameters refer to the same memory location.

Applications

  • The pass-by-reference method is used when we want to pass a large amount of data to avoid unnecessary memory and time consumption for copying the parameters.
  • It is used where we want to modify the actual parameters from the function.
  • It is used to pass arrays and strings to the function.

Passing by reference in programming allows functions to directly access and modify the values of variables, making it efficient for large data and avoiding memory duplication. It’s valuable for updating values and can be particularly useful when working with complex data structures.  

Please Login to comment...

Similar reads.

author

  • Geeks Premier League 2023
  • Geeks Premier League
  • CBSE Exam Format Changed for Class 11-12: Focus On Concept Application Questions
  • 10 Best Waze Alternatives in 2024 (Free)
  • 10 Best Squarespace Alternatives in 2024 (Free)
  • Top 10 Owler Alternatives & Competitors in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn C++

12.3 — Lvalue references

In C++, a reference is an alias for an existing object. Once a reference has been defined, any operation on the reference is applied to the object being referenced.

Key insight

A reference is essentially identical to the object being referenced.

This means we can use a reference to read or modify the object being referenced. Although references might seem silly, useless, or redundant at first, references are used everywhere in C++ (we’ll see examples of this in a few lessons).

You can also create references to functions, though this is done less often.

Modern C++ contains two types of references: lvalue references , and rvalue references . In this chapter, we’ll discuss lvalue references.

Related content

Because we’ll be talking about lvalues and rvalues in this lesson, please review 12.2 -- Value categories (lvalues and rvalues) if you need a refresher on these terms before proceeding.

Rvalue references are covered in the chapter on move semantics ( chapter 22 ).

Lvalue reference types

An lvalue reference (commonly just called a reference since prior to C++11 there was only one type of reference) acts as an alias for an existing lvalue (such as a variable).

To declare an lvalue reference type, we use an ampersand (&) in the type declaration:

Lvalue reference variables

One of the things we can do with an lvalue reference type is create an lvalue reference variable. An lvalue reference variable is a variable that acts as a reference to an lvalue (usually another variable).

To create an lvalue reference variable, we simply define a variable with an lvalue reference type:

In the above example, the type int& defines ref as an lvalue reference to an int, which we then initialize with lvalue expression x . Thereafter, ref and x can be used synonymously. This program thus prints:

From the compiler’s perspective, it doesn’t matter whether the ampersand is “attached” to the type name ( int& ref ) or the variable’s name ( int &ref ), and which you choose is a matter of style. Modern C++ programmers tend to prefer attaching the ampersand to the type, as it makes clearer that the reference is part of the type information, not the identifier.

Best practice

When defining a reference, place the ampersand next to the type (not the reference variable’s name).

For advanced readers

For those of you already familiar with pointers, the ampersand in this context does not mean “address of”, it means “lvalue reference to”.

Modifying values through an lvalue reference

In the above example, we showed that we can use a reference to read the value of the object being referenced. We can also use a reference to modify the value of the object being referenced:

This code prints:

In the above example, ref is an alias for x , so we are able to change the value of x through either x or ref .

Initialization of lvalue references

Much like constants, all references must be initialized.

When a reference is initialized with an object (or function), we say it is bound to that object (or function). The process by which such a reference is bound is called reference binding . The object (or function) being referenced is sometimes called the referent .

Lvalue references must be bound to a modifiable lvalue.

Lvalue references can’t be bound to non-modifiable lvalues or rvalues (otherwise you’d be able to change those values through the reference, which would be a violation of their const-ness). For this reason, lvalue references are occasionally called lvalue references to non-const (sometimes shortened to non-const reference ).

In most cases, the type of the reference must match the type of the referent (there are some exceptions to this rule that we’ll discuss when we get into inheritance):

Lvalue references to void are disallowed (what would be the point?).

References can’t be reseated (changed to refer to another object)

Once initialized, a reference in C++ cannot be reseated , meaning it cannot be changed to reference another object.

New C++ programmers often try to reseat a reference by using assignment to provide the reference with another variable to reference. This will compile and run -- but not function as expected. Consider the following program:

Perhaps surprisingly, this prints:

When a reference is evaluated in an expression, it resolves to the object it’s referencing. So ref = y doesn’t change ref to now reference y . Rather, because ref is an alias for x , the expression evaluates as if it was written x = y -- and since y evaluates to value 6 , x is assigned the value 6 .

Lvalue reference scope and duration

Reference variables follow the same scoping and duration rules that normal variables do:

References and referents have independent lifetimes

With one exception (that we’ll cover next lesson), the lifetime of a reference and the lifetime of its referent are independent. In other words, both of the following are true:

  • A reference can be destroyed before the object it is referencing.
  • The object being referenced can be destroyed before the reference.

When a reference is destroyed before the referent, the referent is not impacted. The following program demonstrates this:

The above prints:

When ref dies, variable x carries on as normal, blissfully unaware that a reference to it has been destroyed.

Dangling references

When an object being referenced is destroyed before a reference to it, the reference is left referencing an object that no longer exists. Such a reference is called a dangling reference . Accessing a dangling reference leads to undefined behavior.

Dangling references are fairly easy to avoid, but we’ll show a case where this can happen in practice in lesson 12.12 -- Return by reference and return by address .

References aren’t objects

Perhaps surprisingly, references are not objects in C++. A reference is not required to exist or occupy storage. If possible, the compiler will optimize references away by replacing all occurrences of a reference with the referent. However, this isn’t always possible, and in such cases, references may require storage.

This also means that the term “reference variable” is a bit of a misnomer, as variables are objects with a name, and references aren’t objects.

Because references aren’t objects, they can’t be used anywhere an object is required (e.g. you can’t have a reference to a reference, since an lvalue reference must reference an identifiable object). In cases where you need a reference that is an object or a reference that can be reseated, std::reference_wrapper (which we cover in lesson 23.3 -- Aggregation ) provides a solution.

As an aside…

Consider the following variables:

Because ref2 (a reference) is initialized with ref1 (a reference), you might be tempted to conclude that ref2 is a reference to a reference. It is not. Because ref1 is a reference to var , when used in an expression (such as an initializer), ref1 evaluates to var . So ref2 is just a normal lvalue reference (as indicated by its type int& ), bound to var .

A reference to a reference (to an int ) would have syntax int&& -- but since C++ doesn’t support references to references, this syntax was repurposed in C++11 to indicate an rvalue reference (which we cover in lesson 22.2 -- R-value references ).

Question #1

Determine what values the following program prints by yourself (do not compile the program).

Show Solution

Because ref is bound to x , x and ref are synonymous, so they will always print the same value. The line ref = y assigns the value of y (2) to ref -- it does not change ref to reference y . The subsequent line y = 3 only changes y .

guest

  • Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

ISO C++ committee meeting

March 18-23, Tokyo, Japan

April 17-20, Bristol, UK

using std::cpp 2024

April 24-26, Leganes, Spain

Pure Virtual C++ 2024

April 30, Online  

C++ Now 2024

May 7-12, Aspen, CO, USA

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

value vs ref semantics

Reference and value semantics, what is value and/or reference semantics, and which is best in c++.

With reference semantics, assignment is a pointer-copy (i.e., a reference ). Value (or “copy”) semantics mean assignment copies the value, not just the pointer. C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.

Pros of reference semantics: flexibility and dynamic binding (you get dynamic binding in C++ only when you pass by pointer or pass by reference, not when you pass by value).

Pros of value semantics: speed. “Speed” seems like an odd benefit for a feature that requires an object (vs. a pointer) to be copied, but the fact of the matter is that one usually accesses an object more than one copies the object, so the cost of the occasional copies is (usually) more than offset by the benefit of having an actual object rather than a pointer to an object.

There are three cases when you have an actual object as opposed to a pointer to an object: local objects, global/ static objects, and fully contained member objects in a class. The most important of these is the last (“composition”).

More info about copy-vs-reference semantics is given in the next FAQs. Please read them all to get a balanced perspective. The first few have intentionally been slanted toward value semantics, so if you only read the first few of the following FAQs, you’ll get a warped perspective.

Assignment has other issues (e.g., shallow vs. deep copy) which are not covered here.

What is “ virtual data,” and how-can / why-would I use it in C++?

virtual data allows a derived class to change the exact class of a base class’s member object. virtual data isn’t strictly “supported” by C++, however it can be simulated in C++. It ain’t pretty, but it works.

To simulate virtual data in C++, the base class must have a pointer to the member object, and the derived class must provide a new object to be pointed to by the base class’s pointer. The base class would also have one or more normal constructors that provide their own referent (again via new ), and the base class’s destructor would delete the referent.

For example, class Stack might have an Array member object (using a pointer), and derived class StretchableStack might override the base class member data from Array to StretchableArray . For this to work, StretchableArray would have to inherit from Array , so Stack would have an Array* . Stack ’s normal constructors would initialize this Array* with a new Array , but Stack would also have a (possibly protected ) constructor that would accept an Array* from a derived class. StretchableStack ’s constructor would provide a new StretchableArray to this special constructor.

  • Easier implementation of StretchableStack (most of the code is inherited)
  • Users can pass a StretchableStack as a kind-of Stack
  • Adds an extra layer of indirection to access the Array
  • Adds some extra freestore allocation overhead (both new and delete )
  • Adds some extra dynamic binding overhead (reason given in next FAQ)

In other words, we succeeded at making our job easier as the implementer of StretchableStack , but all our users pay for it . Unfortunately the extra overhead was imposed on both users of StretchableStack and on users of Stack .

Please read the rest of this section. ( You will not get a balanced perspective without the others. )

What’s the difference between virtual data and dynamic data?

The easiest way to see the distinction is by an analogy with virtual functions : A virtual member function means the declaration (signature) must stay the same in derived classes, but the definition (body) can be overridden. The overriddenness of an inherited member function is a static property of the derived class; it doesn’t change dynamically throughout the life of any particular object, nor is it possible for distinct objects of the derived class to have distinct definitions of the member function.

Now go back and re-read the previous paragraph, but make these substitutions:

  • “member function” → “member object”
  • “signature” → “type”
  • “body” → “exact class”

After this, you’ll have a working definition of virtual data.

Another way to look at this is to distinguish “per-object” member functions from “dynamic” member functions. A “per-object” member function is a member function that is potentially different in any given instance of an object, and could be implemented by burying a function pointer in the object; this pointer could be const , since the pointer will never be changed throughout the object’s life. A “dynamic” member function is a member function that will change dynamically over time; this could also be implemented by a function pointer, but the function pointer would not be const.

Extending the analogy, this gives us three distinct concepts for data members:

  • virtual data: the definition ( class ) of the member object is overridable in derived classes provided its declaration (“type”) remains the same, and this overriddenness is a static property of the derived class
  • per-object-data: any given object of a class can instantiate a different conformal (same type) member object upon initialization (usually a “wrapper” object), and the exact class of the member object is a static property of the object that wraps it
  • dynamic-data: the member object’s exact class can change dynamically over time

The reason they all look so much the same is that none of this is “supported” in C++. It’s all merely “allowed,” and in this case, the mechanism for faking each of these is the same: a pointer to a (probably abstract) base class. In a language that made these “first class” abstraction mechanisms, the difference would be more striking, since they’d each have a different syntactic variant.

Should I normally use pointers to freestore allocated objects for my data members, or should I use “composition”?

Composition.

Your member objects should normally be “contained” in the composite object (but not always; “wrapper” objects are a good example of where you want a pointer/reference; also the N-to-1-uses-a relationship needs something like a pointer/reference).

There are three reasons why fully contained member objects (“composition”) has better performance than pointers to freestore-allocated member objects:

  • Extra layer of indirection every time you need to access the member object
  • Extra freestore allocations ( new in constructor, delete in destructor)
  • Extra dynamic binding (reason given below)

What are relative costs of the 3 performance hits associated with allocating member objects from the freestore?

The three performance hits are enumerated in the previous FAQ:

  • By itself, an extra layer of indirection is small potatoes
  • Freestore allocations can be a performance issue (the performance of the typical implementation of malloc() degrades when there are many allocations; OO software can easily become “freestore bound” unless you’re careful)
  • The extra dynamic binding comes from having a pointer rather than an object. Whenever the C++ compiler can know an object’s exact class, virtual function calls can be statically bound, which allows inlining. Inlining allows zillions (would you believe half a dozen :-) optimization opportunities such as procedural integration, register lifetime issues, etc. The C++ compiler can know an object’s exact class in three circumstances: local variables, global/ static variables, and fully-contained member objects

Thus fully-contained member objects allow significant optimizations that wouldn’t be possible under the “member objects-by-pointer” approach. This is the main reason that languages which enforce reference-semantics have “inherent” performance challenges.

Note: Please read the next three FAQs to get a balanced perspective!

Are “ inline virtual ” member functions ever actually “inlined”?

Occasionally…

When the object is referenced via a pointer or a reference, a call to a virtual function generally cannot be inlined, since the call must be resolved dynamically. Reason: the compiler can’t know which actual code to call until run-time (i.e., dynamically), since the code may be from a derived class that was created after the caller was compiled.

Therefore the only time an inline virtual call can be inlined is when the compiler knows the “exact class” of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/ static object, or a fully contained object inside a composite. This situation can sometimes happen even with a pointer or reference, for example when functions get inlined, access through a pointer or reference may become direct access on the object.

Note that the difference between inlining and non-inlining is normally much more significant than the difference between a regular function call and a virtual function call. For example, the difference between a regular function call and a virtual function call is often just two extra memory references, but the difference between an inline function and a non- inline function can be as much as an order of magnitude (for zillions of calls to insignificant member functions, loss of inlining virtual functions can result in 25X speed degradation! [Doug Lea, “Customization in C++,” proc Usenix C++ 1990]).

A practical consequence of this insight: don’t get bogged down in the endless debates (or sales tactics!) of compiler/language vendors who compare the cost of a virtual function call on their language/compiler with the same on another language/compiler. Such comparisons are largely meaningless when compared with the ability of the language/compiler to “ inline expand” member function calls. I.e., many language implementation vendors make a big stink about how good their dispatch strategy is, but if these implementations don’t inline member function calls, the overall system performance would be poor, since it is inlining — not dispatching— that has the greatest performance impact.

Here is an example of where virtual calls can be inlined even through a reference. The following code is all in the same translation unit, or otherwise organized such that the optimizer can see all of this code at once.

The compiler is free to transform main as follows:

It is now able to inline the virtual function calls.

Note: Please read the next two FAQs to see the other side of this coin!

Sounds like I should never use reference semantics, right?

Reference semantics are A Good Thing. We can’t live without pointers. We just don’t want our software to be One Gigantic Rats Nest Of Pointers. In C++, you can pick and choose where you want reference semantics (pointers/references) and where you’d like value semantics (where objects physically contain other objects etc). In a large system, there should be a balance. However if you implement absolutely everything as a pointer, you’ll get enormous speed hits.

Objects near the problem skin are larger than higher level objects. The identity of these “problem space” abstractions is usually more important than their “value.” Thus reference semantics should be used for problem-space objects.

Note that these problem space objects are normally at a higher level of abstraction than the solution space objects, so the problem space objects normally have a relatively lower frequency of interaction. Therefore C++ gives us an ideal situation: we choose reference semantics for objects that need unique identity or that are too large to copy, and we can choose value semantics for the others. Thus the highest frequency objects will end up with value semantics, since we install flexibility where it doesn’t hurt us (only), and we install performance where we need it most!

These are some of the many issues that come into play with real OO design. OO/C++ mastery takes time and high quality training. If you want a powerful tool, you’ve got to invest.

Don’t stop now! Read the next FAQ too!!

Does the poor performance of reference semantics mean I should pass-by-value?

The previous FAQ were talking about member objects, not parameters. Generally, objects that are part of an inheritance hierarchy should be passed by reference or by pointer, not by value, since only then do you get the (desired) dynamic binding (pass-by-value doesn’t mix with inheritance, since larger derived class objects get sliced when passed by value as a base class object).

Unless compelling reasons are given to the contrary, member objects should be by value and parameters should be by reference. The discussion in the previous few FAQs indicates some of the “compelling reasons” for when member objects should be by reference.

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

Code With C

The Way to Programming

  • C Tutorials
  • Java Tutorials
  • Python Tutorials
  • PHP Tutorials
  • Java Projects

C++ Can You Reassign a Reference? Reference Reassignment Rules

CodeLikeAGirl

Understanding References in C++

Alright, folks! Let’s talk C++ and dive into the nitty-gritty of references. 🚀

What Are References in C++?

So, what in the tech world are references? Well, in C++, a reference is essentially an alias, a nickname if you will, for a variable. It provides us with an alternative name to access the same memory location. It’s like moving into a new apartment and telling your buddy, “Hey, I live at the same address as you!”

Now, how do we create a reference in C++? It’s as easy as apple pie! You slap an ampersand (&) after the type in the declaration and link it to an existing variable. Voilà! You’ve got yourself a reference.

How Are References Different from Pointers?

Ah, references and pointers. They’re like the Batman and Robin of C++ – similar yet different. While pointers can be null and can point to different variables, references are always tied to the same object and can’t be null. Think of it this way: Pointers are like treasure maps leading to a chest of gold, and references are like having a GPS tracker pinpointing the exact location of the treasure all the time. No getting lost there!

Reassigning References in C++

Now, let’s get down to brass tacks. Can you reassign a reference in C++? It’s the million-dollar question, isn’t it?

Can You Reassign a Reference in C++?

Well, I hate to break it to you, but once a reference is initialized to refer to an object, it sticks to that object like glue. You can’t yank it off and stick it onto another object. That’s the deal with references – loyalty to the core!

What Happens When You Try to Reassign a Reference?

So, here’s the scoop. If you try to reassign a reference in C++, you’re in for a wild ride. 🎢 The compiler’s going to give you the stink eye and probably even throw a fit! It’ll raise an eyebrow at your audacity and promptly give you a good scolding. In short, it’s a big no-no in the world of C++.

Reference Reassignment Rules

Let’s lay down the law on the rules of reference reassignment. 📜

Understanding the Restrictions on Reference Reassignment

You see, the whole shebang of references is about being tied down to one single object. It’s like being in an exclusive relationship – no room for wandering eyes here! You’re committed to that object for the long haul.

Common Errors When Attempting to Reassign References

When folks try to reassign references in C++, it’s like trying to tame a wild stallion. It’s just not happening. 🐎 You’ll get some fancy error messages, like “cannot change the value of a reference” or “reassignment of reference is invalid.” The compiler has a sharp eye and won’t let this slide!

Best Practices for Using References in C++

Alright, pals, let’s chat about some best practices when dealing with references in C++.

When to Use References Instead of Pointers

References are handy when you want to avoid null pointers and when you’re dealing with function parameters. They’re like a trusty sidekick giving you the right info at the right time.

How to Avoid Errors When Working with References

First off, don’t even think about trying to reassign a reference. It’s like trying to teach a fish to climb a tree – futile! Also, remember that the original object must still exist when using a reference. None of that disappearing act allowed!

In the grand scheme of things, references in C++ play by their own set of rules. They’re loyal, unwavering, and fiercely tied to their beloved objects. You can’t just play musical chairs with them and expect everything to be hunky-dory.

Summary of Reference Reassignment in C++

To sum it all up, attempting to reassign a reference in C++ is a cardinal sin. It’s a strict no-go and the compiler won’t hesitate to put you in your place.

Final Thoughts on Using References in C++

References are powerful allies in the world of C++, but they have their own code of conduct. So, if you’re dealing with references, remember: once assigned, they’re there to stay. 🛠️

Oh, and if you’ve got any stories or experiences with references in C++, hit me up! Let’s swap tales of triumphs and tribulations in the wild world of coding. Cheers, and happy coding, amigos! 🌟

Program Code – C++ Can You Reassign a Reference? Reference Reassignment Rules

Code output:.

ref initially points to a: 10 After ‘ref = b’, ref is still pointing to a, with a new value: 20 Value of a after ‘ref = b’: 20 Value of b remains unchanged: 20

Code Explanation:

Here’s the breakdown of this code tooth and nail, folks!

First, we’re bringing in the big guns with <iostream>, cos hey, who doesn’t wanna have a chatty program?

We’ve got our main function serving as the grand entrance. Got two vars, a and b, holding values 10 and 20. So far, nothing to write home about.

Then the plot thickens! We introduce a reference, ref, tying the knot with a. It’s like a’s shadow, mimics everything it does. We make a show of it with a cout statement.

Next up, the twist – we tell ref that it should cozy up to b by doing a ‘ref = b’. But surprise, surprise! Ref doesn’t actually jump ship to b. Nope! It just gives a the personality of b. We’re talking identity theft; a transforms into a 20. Another cout, because showing is better than telling.

We check on b, and it’s cool, sitting untouched. Phew!

But hold your horses – what if we get greedy and try to re-declare ref to b for real? Compiler’s gonna shut that down faster than you say ‘oops’. A reference, once set, is like a loyal pup; it can’t be re-homed.

End scene. Return 0 – cause we’re all about clean exits here.

You Might Also Like

The significance of ‘c’ in c programming language, c programming languages: understanding the basics and beyond, exploring the c programming language: from basics to advanced concepts, object-oriented programming: the pillar of modern software development, object-oriented coding: best practices and techniques.

Avatar photo

Leave a Reply Cancel reply

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

Latest Posts

79 Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

68 Enhanced Security Network Coding System Project for Two-Way Relay Networks

Enhanced Security Network Coding System Project for Two-Way Relay Networks

88 Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

72 Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

codewithc 61 1 Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Privacy overview.

Sign in to your account

Username or Email Address

Remember Me

This browser is no longer supported.

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

Rvalue reference declarator: &&

  • 7 contributors

Holds a reference to an rvalue expression.

rvalue-reference-type-id :   type-specifier-seq && attribute-specifier-seq opt ptr-abstract-declarator opt

Rvalue references enable you to distinguish an lvalue from an rvalue. Lvalue references and rvalue references are syntactically and semantically similar, but they follow slightly different rules. For more information about lvalues and rvalues, see Lvalues and Rvalues . For more information about lvalue references, see Lvalue Reference Declarator: & .

The following sections describe how rvalue references support the implementation of move semantics and perfect forwarding .

Move semantics

Rvalue references support the implementation of move semantics , which can significantly increase the performance of your applications. Move semantics enables you to write code that transfers resources (such as dynamically allocated memory) from one object to another. Move semantics works because it enables transfer of resources from temporary objects: ones that can't be referenced elsewhere in the program.

To implement move semantics, you typically provide a move constructor, and optionally a move assignment operator ( operator= ), to your class. Copy and assignment operations whose sources are rvalues then automatically take advantage of move semantics. Unlike the default copy constructor, the compiler doesn't provide a default move constructor. For more information about how to write and use a move constructor, see Move constructors and move assignment operators .

You can also overload ordinary functions and operators to take advantage of move semantics. Visual Studio 2010 introduces move semantics into the C++ Standard Library. For example, the string class implements operations that use move semantics. Consider the following example that concatenates several strings and prints the result:

Before Visual Studio 2010, each call to operator+ allocates and returns a new temporary string object (an rvalue). operator+ can't append one string to the other because it doesn't know whether the source strings are lvalues or rvalues. If the source strings are both lvalues, they might be referenced elsewhere in the program, and so must not be modified. You can modify operator+ to take rvalues by using rvalue references, which can't be referenced elsewhere in the program. With this change, operator+ can now append one string to another. The change significantly reduces the number of dynamic memory allocations that the string class must make. For more information about the string class, see basic_string Class .

Move semantics also helps when the compiler can't use Return Value Optimization (RVO) or Named Return Value Optimization (NRVO). In these cases, the compiler calls the move constructor if the type defines it.

To better understand move semantics, consider the example of inserting an element into a vector object. If the capacity of the vector object is exceeded, the vector object must reallocate enough memory for its elements, and then copy each element to another memory location to make room for the inserted element. When an insertion operation copies an element, it first creates a new element. Then it calls the copy constructor to copy the data from the previous element to the new element. Finally, it destroys the previous element. Move semantics enables you to move objects directly without having to make expensive memory allocation and copy operations.

To take advantage of move semantics in the vector example, you can write a move constructor to move data from one object to another.

For more information about the introduction of move semantics into the C++ Standard Library in Visual Studio 2010, see C++ Standard Library .

Perfect forwarding

Perfect forwarding reduces the need for overloaded functions and helps avoid the forwarding problem. The forwarding problem can occur when you write a generic function that takes references as its parameters. If it passes (or forwards ) these parameters to another function, for example, if it takes a parameter of type const T& , then the called function can't modify the value of that parameter. If the generic function takes a parameter of type T& , then the function can't be called by using an rvalue (such as a temporary object or integer literal).

Ordinarily, to solve this problem, you must provide overloaded versions of the generic function that take both T& and const T& for each of its parameters. As a result, the number of overloaded functions increases exponentially with the number of parameters. Rvalue references enable you to write one version of a function that accepts arbitrary arguments. Then that function can forward them to another function as if the other function had been called directly.

Consider the following example that declares four types, W , X , Y , and Z . The constructor for each type takes a different combination of const and non- const lvalue references as its parameters.

Suppose you want to write a generic function that generates objects. The following example shows one way to write this function:

The following example shows a valid call to the factory function:

However, the following example doesn't contain a valid call to the factory function. It's because factory takes lvalue references that are modifiable as its parameters, but it's called by using rvalues:

Ordinarily, to solve this problem, you must create an overloaded version of the factory function for every combination of A& and const A& parameters. Rvalue references enable you to write one version of the factory function, as shown in the following example:

This example uses rvalue references as the parameters to the factory function. The purpose of the std::forward function is to forward the parameters of the factory function to the constructor of the template class.

The following example shows the main function that uses the revised factory function to create instances of the W , X , Y , and Z classes. The revised factory function forwards its parameters (either lvalues or rvalues) to the appropriate class constructor.

Properties of rvalue references

You can overload a function to take an lvalue reference and an rvalue reference.

By overloading a function to take a const lvalue reference or an rvalue reference, you can write code that distinguishes between non-modifiable objects (lvalues) and modifiable temporary values (rvalues). You can pass an object to a function that takes an rvalue reference unless the object is marked as const . The following example shows the function f , which is overloaded to take an lvalue reference and an rvalue reference. The main function calls f with both lvalues and an rvalue.

This example produces the following output:

In this example, the first call to f passes a local variable (an lvalue) as its argument. The second call to f passes a temporary object as its argument. Because the temporary object can't be referenced elsewhere in the program, the call binds to the overloaded version of f that takes an rvalue reference, which is free to modify the object.

The compiler treats a named rvalue reference as an lvalue and an unnamed rvalue reference as an rvalue.

Functions that take an rvalue reference as a parameter treat the parameter as an lvalue in the body of the function. The compiler treats a named rvalue reference as an lvalue. It's because a named object can be referenced by several parts of a program. It's dangerous to allow multiple parts of a program to modify or remove resources from that object. For example, if multiple parts of a program try to transfer resources from the same object, only the first transfer succeeds.

The following example shows the function g , which is overloaded to take an lvalue reference and an rvalue reference. The function f takes an rvalue reference as its parameter (a named rvalue reference) and returns an rvalue reference (an unnamed rvalue reference). In the call to g from f , overload resolution selects the version of g that takes an lvalue reference because the body of f treats its parameter as an lvalue. In the call to g from main , overload resolution selects the version of g that takes an rvalue reference because f returns an rvalue reference.

In the example, the main function passes an rvalue to f . The body of f treats its named parameter as an lvalue. The call from f to g binds the parameter to an lvalue reference (the first overloaded version of g ).

  • You can cast an lvalue to an rvalue reference.

The C++ Standard Library std::move function enables you to convert an object to an rvalue reference to that object. You can also use the static_cast keyword to cast an lvalue to an rvalue reference, as shown in the following example:

Function templates deduce their template argument types and then use reference collapsing rules.

A function template that passes (or forwards ) its parameters to another function is a common pattern. It's important to understand how template type deduction works for function templates that take rvalue references.

If the function argument is an rvalue, the compiler deduces the argument to be an rvalue reference. For example, assume you pass an rvalue reference to an object of type X to a function template that takes type T&& as its parameter. Template argument deduction deduces T to be X , so the parameter has type X&& . If the function argument is an lvalue or const lvalue, the compiler deduces its type to be an lvalue reference or const lvalue reference of that type.

The following example declares one structure template and then specializes it for various reference types. The print_type_and_value function takes an rvalue reference as its parameter and forwards it to the appropriate specialized version of the S::print method. The main function demonstrates the various ways to call the S::print method.

To resolve each call to the print_type_and_value function, the compiler first does template argument deduction. The compiler then applies reference collapsing rules when it replaces the parameter types with the deduced template arguments. For example, passing the local variable s1 to the print_type_and_value function causes the compiler to produce the following function signature:

The compiler uses reference collapsing rules to reduce the signature:

This version of the print_type_and_value function then forwards its parameter to the correct specialized version of the S::print method.

The following table summarizes the reference collapsing rules for template argument type deduction:

Template argument deduction is an important element of implementing perfect forwarding. The Perfect forwarding section describes perfect forwarding in more detail.

Rvalue references distinguish lvalues from rvalues. To improve the performance of your applications, they can eliminate the need for unnecessary memory allocations and copy operations. They also enable you to write a function that accepts arbitrary arguments. That function can forward them to another function as if the other function had been called directly.

Expressions with unary operators Lvalue reference declarator: & Lvalues and rvalues Move constructors and move assignment operators (C++) C++ Standard Library

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

Due: Mon Apr 8 11:59 pm No late submissions accepted.

No late submissions are accepted on this assignment (except for OAE accommodations or granted extensions). The deadline is firm without exception.

Assignment by Michael Chang, Julie Zelenski, and Chris Gregg, with modifications by Nick Troccoli

We'll discuss the terminal and text editors even more during lecture 2, so that lecture material is needed to get the starter project, edit files, and complete the intruder detection portion of the assignment. However, prior to then, you can get your computer set up to log into the myth machines by installing a terminal program, review the course syllabus, and complete the honor code survey linked below.

Learning Goals

The goals for this assignment are for you to get familiar with working in the Unix environment, and editing/building/running C programs.

Unix and C Resources

The pages in the Handouts dropdown above have information, including videos, for various Unix commands, tools, and more that we'll be using this quarter. We highly recommend reading through the getting started guide and unix guide and trying out various commands and tools yourself, to get practice. In particular, some of the activities in this assignment will rely on information you will need to read up on there. Note that you don't need to memorize all the information, but you may start to memorize lots of commands just by repetition.

Before starting the assignment, double-check that you are comfortable with these Unix fundamentals - discussed in the getting started guide.

View Getting Started Guide

  • Log in to myth
  • Did you create a CS107 directory to hold and organize your work?
  • Can you find the code we're showing off in lecture?
  • You should be able to create a new file, edit its contents, save, and exit.
  • For emacs , you should be able to interact via the mouse (e.g. selecting text, scrolling, etc.)
  • If you encounter a command that is new to you, how can you get more information about it?
  • Have you tried using tab-completion to avoid manually typing long commands/paths?

Additionally, take a look at the guide in the assignments dropdown about working on assignments. It outlines everything you need to know about working through a CS107 assignment, from getting the starter code to testing to submitting. We will refer to this document many, many times throughout this assignment, so keep it handy as you work through this page.

View Assignments Guide

Cloning The Assignment

To get started on the assignment, you must "clone" the starter code to get a copy you can work on. Check out the assignments guide for how to do this.

If you attempt to clone and receive an error that the repository does not exist :

  • double-check for typos in the path. The path needs to be typed exactly as specified. This includes the odd-looking $USER at end, which is a environment variable that expands into your username automatically.
  • be sure you are logged into myth

If you confirm you are on a myth system and your correctly-typed path is not available, this indicates that you were not on the Axess enrollment list at the time we created the student starter code projects. Please send an email to the course staff and tell us your username so we can manually set up the starter code for you. Please make sure to enroll in Axess as soon as possible so that the starter code is automatically generated for you in the future.

Provided Files

The starter project contains the following:

  • readme.txt : a text file where you will answer questions for the assignment
  • triangle.c , Makefile and custom_tests : used to build and test the triangle program
  • SANITY.ini : the configuration for Sanity Check. You can ignore this file.
  • server_files : a folder that pertains to the first part of the assignment.
  • triangle_soln : an executable solution for the Triangle program. You can run this program to see how a completed solution program should behave. This program is also used to check correctness in sanity check.
  • tools : contains symbolic links to the sanitycheck and submit programs for testing and submitting your work.

Symbolic links mean that the files actually live in the CS107 class directory, but appear just like normal files in your starter code folder. Note that the shared directories are not editable by you, so you will not be able to create, edit, or delete files within these directories, since they actually live in the CS107 class directory.

1. Enrollment Confirmation

In order to complete your enrollment in CS107, you must fill out the readme with some information about you, confirm your ability to attend the final exam and accept the course Honor Code policy.

Open the readme.txt file in your editor now and edit as appropriate.

As part of this, you must complete the Honor Code Form. When grading your assign0, we will check that you made a submission through this form, so please make sure to fill it out!

Access the Honor Code Form

Course TODOs:

Once you have done this, also complete the following setup tasks:

  • Join our course discussion forum by visiting the Getting Help page.
  • Remember to submit your lab preferences (not first-come-first-serve) between Tue Apr 2 12:00 pm PDT and Sun Apr 7 9:00 pm PDT .

2. Intruder Detection

For this activity, you will investigate a simulated break-in and answer the questions below. Type your answers into the readme.txt file. For each, briefly describe (in 1-2 sentences) how you arrived at that answer and what Unix commands you used (text editor keyboard shortcuts (e.g. emacs commands) do not classify as Unix commands).

Activity Learning Goals: In class we have taught you the basics of Unix: how to login to myth, how to make directories, and how to list files. In this activity, you will further develop your Unix skills by understanding how to use common Unix commands beyond what we know so far. The how-to's of many of the commands you will learn are available on our CS107 Unix guide, under "Handouts". We recommend you browse this guide as you complete this activity:

View Unix Guide

Situation: An intruder had broken into your dorm's unix-based server and deleted most of the files! Fortunately, there is a backup of the server contents, but before restoring the files, you'd like to know who the intruder was and what they did. With your newly-developed Unix skills, you are just the expert to help investigate.

The key files are available in the directory samples/server_files , which you can access within your assign0 directory.

The first thing you want to determine is the username of the intruder. The server is used by many different users. Each user has a home directory under home/ . For example, the home directory for the user bob would be the path home/bob . The file users.list contains a list of all the authorized users. In an uncompromised system, each home directory would correspond to a user on the authorized list and vice versa. The intruder is not an authorized user and they gained illicit access by inserting their own home directory onto the system. This means there is one home directory that doesn't belong, and your job is to find it.

Manually cross-comparing the users.list to the directory contents would be time-consuming. Instead, what Unix commands can you use to help? Check out the Unix guide for some ideas.

Hint: the samples/ folder and everything inside it is a shared, read-only folder for all students for this assignment. For this reason, you can't create any new files within samples , and you can't create new files outside of samples from within the samples folder. If you need to create a temporary file, try creating it directly inside your assign0 directory instead.

  • What is the username of the intruder? Include the details on how you figured out the answer, and what Unix command(s) you used. You should use Unix commands as much as possible, even if other by-hand alternatives exist (as a clarification, commands within a text editor - e.g. emacs - are not Unix commands).

Now that you know the intruder's username, you can examine the files in intruder's home directory to learn what they were up to. Though the intruder tried to delete all the home directory files as part of covering their tracks, you can see that this supposedly empty directory is still taking up space. Perhaps something interesting was overlooked?

Take a closer look to find out what files have been left behind. Open each of the files in the intruder's home directory to see their contents.

  • There is one file in the intruder's home directory that provides critical information about their activities. What file is that and what does it contain? Include the details on how you figured out the answer, and what Unix command(s) you used. You should use Unix commands as much as possible, even if other by-hand alternatives exist (as a clarification, commands within a text editor - e.g. emacs - are not Unix commands).

You believe that the intruder used sudo to execute some commands as a privileged user. You want to identify those commands, but the file is rather long to comb through by hand. What Unix command can you use to extract the information you seek?

  • Which commands did the intruder execute using sudo ? Include the details on how you figured out the answer, and what Unix command(s) you used. You should use Unix commands as much as possible, even if other by-hand alternatives exist (as a clarification, commands within a text editor - e.g. emacs - are not Unix commands).

3. C Introduction

The final task of the assignment gives you practice using the Unix development tools to edit, build, run, and test a short C program.

In your assign0 folder, type make . This will build the program named triangle . Run the program to see what it does:

You should be rewarded with an ascii representation of Sierpinski's triangle - cool! Try to run make again:

This isn't an error; it simply means that nothing has changed in the program's source, so there isn't anything to re-compile.

Open triangle.c in a text editor and change the value of the #define d value, DEFAULT_LEVELS above main from 3 to 5. After you have saved the file, you must then use make to re-build the program , and then you can run the newly built program to see the bigger triangle. If you forget to re-run make , you will run the original version of the program that has not been updated!

The starter code uses a fixed constant for the number of levels to print. Your task is to extend the program to take an optional command-line argument that allows the user to dictate the number of levels. With no arguments, ./triangle should default to a level 3 triangle, but the user should also be able to provide a numeric argument, e.g. ./triangle 4 or ./triangle 2 , to control the number of levels. If given an unworkable number of levels (anything larger than 8 gets unwieldy and negative would be nonsensical), your program should reject it with a helpful and explanatory message that informs the user how to correct their error, and then terminate early with an exit status of 1 (this indicates something went wrong with the program execution). The best function to do this is the error function; check out the manual pages ( man 3 error ) for more information about this function (Fun fact: man pages have information for both Unix commands and built-in C functions!) One note is that you should specify an errnum of 0 , since we don't need to print out an error message corresponding to a specific error code. Try to figure out the values for the remaining parameters. You must exactly match the error message of the sample solution . Note : You may assume that the user will enter an integer value, and do not have to worry about handling arguments that are not valid integers. If the user specifies multiple command-line arguments, you should use just the first one .

When applicable, you should define constants in your program rather than using "magic numbers", which are numbers hardcoded into your program. See the starter code for an example of how to do this in C.

In order to complete this task, the program will need to convert the user's argument (supplied in string form) into an integer. The C library function atoi can be used to do this. Review the man page ( man atoi ) or look in your C reference to get acquainted with this function.

Now let's test the program implementation. The Sanity Check tool is included in the assignment starter project, and acts as a testing aid. Read the guide to working on assignments for more information about how to use it.

The default sanitycheck for assign0 has one test that validates the output of the triangle program when given no argument. The unmodified starter program code should pass this test. After you have extended the triangle program to accept an argument, the program should continue to pass the default sanitycheck, but you will need new tests to validate the argument-handling.

You extend sanitycheck to test additional cases by using a custom tests file. The starter project includes a custom_tests file. Open this file in your editor to see the format. Now consider what additional test cases are needed to fully vet the output of your new, improved triangle program. You will need at least two additional tests. Add those tests to this custom_tests file and use these with sanitycheck to validate that your triangle program passes all tests. For more information about how to run your custom tests, check out the guide to working on assignments. For tips on thorough testing, check out our testing guide, linked to from the assignments dropdown.

Once you are finished working and have saved all your changes, check out the guide to working on assignments for how to submit your work. We recommend you do a trial submit in advance of the deadline to familiarize yourself with the process and allow time to work through any snags. You may submit as many times as you would like; we will grade the latest submission.

You should only need to modify the following files for this assignment: readme.txt , triangle.c , custom_tests .

We would also appreciate if you filled out this homework survey to tell us what you think once you submit. We appreciate your feedback!

The assignment is graded out of about 26 functionality points, plus a bucket grade for style. Full credit will be awarded for reasonable answers to the questions in the readme.txt file and a correct modification of triangle.c and custom_tests . This assignment is worth far fewer points than all of our other assignments. But, hey, we expect each and every one of you to earn all of the points on this one!

Post-Assignment Check-in

How did the assignment go for you? We encourage you to take a moment to reflect on how far you've come and what new knowledge and skills you have to take forward. Once you finish this assignment, you should have your environment configured and should be starting to feel comfortable with the command-line interface, navigating the filesystem, using a Unix text editor, and getting around Unix. You're off to a great start!

To help you gauge your progress, for each assignment/lab, we identify some of its takeaways and offer a few thought questions you can use as a self-check on your post-task understanding. If you find the responses don't come easily, it may be a sign a little extra review is warranted. These questions are not to be handed in or graded. You're encouraged to freely discuss these with your peers and course staff to solidify any gaps in your understanding before moving on from a task. They could also be useful as review for our exams.

  • Identify a few different techniques to avoid painstakingly re-typing a long Unix command to execute.
  • How do you copy and paste in your text editor?
  • Explain the purpose and use of the CS107 tools sanitycheck and submit . How do you customize the tests used by sanity check?

Frequently Asked Questions

When i try to run the triangle program in my directory, it responds "command not found". what's wrong.

Unix wants you to instead refer to the program by its full name ./triangle . See our Unix guide for more information.

How do I use the sample executable? How does it relate to sanity check?

Our provided sample executable can be used a reference implementation during testing. Run the solution and your program on the same input and verify the output is the same:

If your program produces the same result as the sample, all is good. You can manually "eyeball" the two results, or run sanitycheck with the provided tests, or your own tests. You can find more information about sanity check in our guide to working on assignments.

reference assignment c

April 2, 2024, update for PowerPoint 2016 (KB5002568)

This article describes update 5002568 for Microsoft PowerPoint 2016 that was released on April 2, 2024.

Be aware that the update in the Microsoft Download Center applies to the Microsoft Installer (.msi)-based edition of Office 2016. It doesn't apply to the Office 2016 Click-to-Run editions, such as Microsoft Office 365 Home. (See  What version of Office am I using? )

Improvements and fixes

This update disables the following features in Microsoft Office 2016 for some specific languages to avoid a file corruption issue:

The Display as icon checkbox in the Insert Object , Convert , and Paste Special dialog boxes.

The Create from file option in the Insert Object dialog box.

The DisplayAsIcon and Link parameters in the Shapes.AddOLEObject method.

Pasting as Picture (Windows Metafile) from the Paste Special dialog box.

Pasting as ppPasteMetafilePicture from the Shapes.PasteSpecial and View.PasteSpecial methods.

How to download and install the update

Microsoft Update

Use Microsoft Update to automatically download and install the update.

Download Center

This update is available to manually download and install from the Microsoft Download Center.

Download update 5002568 for 32-bit version of PowerPoint 2016

Download update 5002568 for 64-bit version of PowerPoint 2016

If you're not sure which platform (32-bit or 64-bit) you're running, see  Am I running 32-bit or 64-bit Office?  Additionally, see  more information about how to download Microsoft support files .

Virus-scan claim

Microsoft scanned this file for viruses by using the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help prevent any unauthorized changes to it.

Update information

Prerequisites

To apply this update, you must have Microsoft PowerPoint 2016 installed.

Restart information

You might have to restart the computer after you install this update.

More information

How to uninstall this update.

Windows 11 and Windows 10

Go to  Start , enter Control Panel in the search box, and then press Enter.

In the Control Panel search box, enter Installed Updates .

In the search results, select  View installed updates .

In the list of updates, locate and select  KB5002568 , and then select  Uninstall .

File information

The English (United States) version of this software update installs files that have the attributes that are listed in the following tables. The dates and times for these files are listed in Coordinated Universal Time (UTC). The dates and times for these files on your local computer are displayed in your local time together with your current daylight saving time (DST) bias. Additionally, the dates and times may change when you perform certain operations on the files.

Learn about the standard  terminology  that is used to describe Microsoft software updates.

The  Office System TechCenter contains the latest administrative updates and strategic deployment resources for all versions of Office.

Facebook

Need more help?

Want more options.

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

reference assignment c

Microsoft 365 subscription benefits

reference assignment c

Microsoft 365 training

reference assignment c

Microsoft security

reference assignment c

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

reference assignment c

Ask the Microsoft Community

reference assignment c

Microsoft Tech Community

reference assignment c

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

Watch CBS News

Solar eclipse maps show 2024 totality path, peak times and how much of the eclipse you can see across the U.S.

By Aliza Chasan

Updated on: April 7, 2024 / 7:29 PM EDT / CBS News

A total solar eclipse crosses North America on April 8, 2024, with parts of 15 U.S. states within the path of totality. Maps show where and when astronomy fans can see the big event . 

The total eclipse will first appear along Mexico's Pacific Coast at around 11:07 a.m. PDT, then travel across a swath of the U.S., from Texas to Maine, and into Canada.

About 31.6 million people live in the path of totality , the area where the moon will fully block out the sun , according to NASA. The path will range between 108 and 122 miles wide. An additional 150 million people live within 200 miles of the path of totality.

Solar eclipse path of totality map for 2024

United states map showing the path of the 2024 solar eclipse and specific regions of what the eclipse duration will be.

The total solar eclipse will start over the Pacific Ocean, and the first location in continental North America that will experience totality is Mexico's Pacific Coast, around 11:07 a.m. PDT on April 8, according to NASA. From there, the path will continue into Texas, crossing more than a dozen states before the eclipse enters Canada in southern Ontario. The eclipse will exit continental North America around 5:16 p.m. NDT from Newfoundland, Canada.

The path of totality includes the following states:

  • Pennsylvania
  • New Hampshire

Small parts of Tennessee and Michigan will also experience the total solar eclipse.

Several major cities across the U.S. are included in the eclipse's path of totality, while many others will see a partial eclipse. Here are some of the best major cities for eclipse viewing — if the weather cooperates :

  • San Antonio, Texas (partially under the path)
  • Austin, Texas
  • Waco, Texas
  • Dallas, Texas
  • Little Rock, Arkansas
  • Indianapolis, Indiana
  • Dayton, Ohio
  • Cleveland, Ohio
  • Buffalo, New York
  • Rochester, New York
  • Syracuse, New York
  • Burlington, Vermont

Map of when the solar eclipse will reach totality across the path

Eclipse map of totality

The eclipse will begin in the U.S. on the afternoon of April 8. It will first be visible as a partial eclipse beginning at 12:06 p.m. CDT near Eagle Pass, Texas, before progressing to totality by about 1:27 p.m. CDT and progressing along its path to the northeast over the next few hours.

NASA shared times for several cities in the path of totality across the U.S. You can also  check your ZIP code on NASA's map  to see when the eclipse will reach you if you're on, or near, the path of totality. 

How much of the eclipse will you see if you live outside of the totality path?

While the April 8 eclipse will cover a wide swath of the U.S., outside the path of totality observers may spot a partial eclipse, where the moon covers some, but not all, of the sun, according to NASA. The closer you are to the path of totality, the larger the portion of the sun that will be hidden.

NASA allows viewers to input a ZIP code and see how much of the sun will be covered in their location.

Could there be cloud cover be during the solar eclipse?

Some areas along the path of totality have a higher likelihood of cloud cover that could interfere with viewing the eclipse. Here is a map showing the historical trends in cloud cover this time of year. 

You can check the latest forecast for your location with our partners at The Weather Channel .

United States map showing the percent of cloud cover in various regions of the eclipse path on April 8. The lakeshore region will be primarily affected.

Where will the solar eclipse reach totality for the longest?

Eclipse viewers near Torreón, Mexico, will get to experience totality for the longest. Totality there will last 4 minutes, 28 seconds, according to NASA. 

Most places along the centerline of the path of totality will see a totality duration between 3.5 and 4 minutes long, according to NASA. Some places in the U.S. come close to the maximum; Kerrville, Texas, will have a totality duration of 4 minutes, 24 seconds.

What is the path of totality for the 2044 solar eclipse?

After the April 8 eclipse, the next total solar eclipse that will be visible from the contiguous U.S. will be on Aug. 23, 2044.

Astronomy fans in the U.S. will have far fewer opportunities to see the 2044 eclipse than the upcoming one on April 8. NASA has not yet made maps available for the 2044 eclipse, but, according to The Planetary Society , the path of totality will only touch three states.

The 2024 eclipse will start in Greenland, pass over Canada and end as the sun sets in Montana, North Dakota and South Dakota, according to the Planetary Society.

Map showing the path of the 2044 total solar eclipse from Greenland, Canada and parts of the United States.

Aliza Chasan is a digital producer at 60 Minutes and CBSNews.com. She has previously written for outlets including PIX11 News, The New York Daily News, Inside Edition and DNAinfo. Aliza covers trending news, often focusing on crime and politics.

More from CBS News

Join these solar eclipse events in NYC & across New York state

New York solar eclipse forecast: See the cloud cover map

Umbraphile explains the thrill of eclipse chasing

Start time for Yankees-Marlins game pushed back due to eclipse

Iowa vs. Connecticut was ESPN’s highest-rated basketball game ever

reference assignment c

CLEVELAND — Women’s college basketball continues to grab the nation’s attention at an unprecedented rate, and the metrics prove it.

The Final Four game between Iowa and Connecticut on Friday night was the most-watched basketball game ever aired on ESPN; an average of 14.2 million viewers tuned in, and the broadcast peaked at 17 million. Iowa defeated U-Conn., 71-69 , to advance to its second consecutive national championship game with star guard Caitlin Clark leading the way. The previous record for an ESPN basketball broadcast was 13.51 million viewers for Game 7 of the 2018 NBA Eastern Conference finals between the Cleveland Cavaliers and Boston Celtics.

Friday’s game surpassed the record for an NCAA women’s broadcast of 12.3 million viewers set by the Iowa-LSU Elite Eight game less than a week ago. That game Monday night was a rematch of the 2023 national championship game won by LSU and featured the star power of Clark and Angel Reese.

“I think the biggest thing is there’s been so many amazing players that have come before us and laid a really solid foundation of what our game has become,” Clark said Friday before the latest record was set. “As a competitor and being involved in this moment, it’s hard for you to wrap your head around.”

The game’s popularity has soared, and Clark has played a significant role. This season, she became NCAA Division I’s all-time leading scorer for men or women, surpassing Pete Maravich’s 3,667 points . Last fall, Iowa held an exhibition game at Kinnick Stadium, where the Hawkeyes play football, and 55,646 attended. Iowa road games sold out repeatedly throughout the season, and Saturday’s open practice sessions at Rocket Mortgage FieldHouse also sold out.

March Madness

The NCAA men’s and women’s basketball tournaments are underway. Get caught up with the men’s bracket and women’s bracket .

The latest: The men’s Final Four is set, with No. 1 seeds Connecticut and Purdue taking on No. 4 seed Alabama and No. 11 seed North Carolina State, respectively, on Saturday night. N.C. State finished the regular season 17-14 and has since made a magical run to earn its spot, while U-Conn. looks every bit the powerhouse it was expected to be. In the women’s tournament, South Carolina knocked off N.C. State to reach Sunday’s title game, while Caitlin Clark’s Iowa took down Connecticut.

Find all of The Post’s latest NCAA tournament updates in our March Madness hub .

reference assignment c

cppreference.com

Std::vector<t,allocator>:: assign.

Replaces the contents of the container.

All iterators, pointers and references to the elements of the container are invalidated. The past-the-end iterator is also invalidated.

[ edit ] Parameters

[ edit ] complexity, [ edit ] example.

The following code uses assign to add several characters to a std:: vector < char > :

[ edit ] See also

  • 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 4 December 2020, at 13:41.
  • This page has been accessed 464,628 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • Personal Finance
  • AP Investigations
  • AP Buyline Personal Finance
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • Election Results
  • Delegate Tracker
  • AP & Elections
  • March Madness
  • AP Top 25 Poll
  • Movie reviews
  • Book reviews
  • Personal finance
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

AP PHOTOS: 10 years after her killing, Anja Niedringhaus’ photos speak for her

FILE - A girl tries to peer through the holes of her burqa as she plays with other children in the old town of Kabul, Afghanistan, April 7, 2013. Despite Associated Press photographer Anja Niedringhaus' reputation as a war photographer, very often she found beauty and joy on assignment. (AP Photo/Anja Niedringhaus, File)

FILE - A girl tries to peer through the holes of her burqa as she plays with other children in the old town of Kabul, Afghanistan, April 7, 2013. Despite Associated Press photographer Anja Niedringhaus’ reputation as a war photographer, very often she found beauty and joy on assignment. (AP Photo/Anja Niedringhaus, File)

FILE - A girl tries to peer through the holes of her burqa as she plays with other children in the old town of Kabul, Afghanistan, Sunday, April 7, 2013. Despite Associated Press photographer Anja Niedringhaus' reputation as a war photographer, very often she found beauty and joy on assignment. (AP Photo/Anja Niedringhaus, File)

FILE - A girl tries to peer through the holes of her burqa as she plays with other children in the old town of Kabul, Afghanistan, Sunday, April 7, 2013. Despite Associated Press photographer Anja Niedringhaus’ reputation as a war photographer, very often she found beauty and joy on assignment. (AP Photo/Anja Niedringhaus, File)

  • Copy Link copied

FILE - A picture of Afghan President Hamid Karzai hangs on a wall in the main room of the district municipality in eastern Kabul on Saturday, March 29, 2014, ahead of the April 5, 2014 election to choose a new president. Associated Press photographer Anja Niedringhaus was best known as a conflict photographer. Her work helped define the wars in Iraq, Afghanistan, and Libya. (AP Photo/Anja Niedringhaus, File)

FILE - An honor guard stands next to men who arrived to mourn the death of late Vice President Field Marshal Mohammed Qasim Fahim outside his house in Kabul, Afghanistan, Monday, March 10, 2014. The influential vice president, a leading commander in the alliance that fought the Taliban who was later accused with other warlords of targeting civilian areas during the country’s civil war, died March 9, 2014. He was 57. (AP Photo/Anja Niedringhaus, File)

FILE - A topless Ukrainian protester is arrested by Swiss police after climbing up a fence at the entrance to the center where the World Economic Forum is held in Davos, Switzerland Saturday, Jan. 28, 2012. The activists are from the group Femen, which had become popular in Ukraine for staging small, half-naked protests against a range of issues including oppression of political opposition. (AP Photo/Anja Niedringhaus, File)

FILE - Serena Williams of the United States reacts after winning against Zheng Jie of China during a third round women’s singles match at the All England Lawn Tennis Championships at Wimbledon, England, Saturday, June 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - A nomad kisses his young daughter while watching his herd in Marjah, Helmand province, Afghanistan on Oct. 20, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Britain’s Mohamed Farah celebrates as he crosses the finish line to win the men’s 5000-meter final during the athletics in the Olympic Stadium at the 2012 Summer Olympics, London, Saturday, Aug. 11, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - An umpire watches the ball as a match unfolds on Court 18, as seen through wooden slats, at the All England Lawn Tennis Championships in Wimbledon, London, Wednesday, June 26, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Boys play soccer during a break at their school in Kandahar, southern Afghanistan, Tuesday, Oct 29, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Pakistani children get ready for class at Malala Yousufzai’s old school in Mingora, Swat Valley, Pakistan on Saturday, Oct 5, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A woman takes a dip in Lake Geneva at sunrise in Geneva, Switzerland on Sunday, July 21, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Afghan Army soldiers gather at a training facility on the outskirts of Kabul, Afghanistan, Wednesday, May 8, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Injured U.S. Marine Cpl. Burness Britt reacts after being lifted onto a medevac helicopter from the U.S. Army’s Task Force Lift “Dust Off,” Charlie Company 1-214 Aviation Regiment on Saturday, June 4, 2011. Britt was wounded in an IED strike near Sangin, in the Helmand Province of southern Afghanistan. During his first operation in Afghanistan he suffered a stroke and became partially paralyzed. (AP Photo/Anja Niedringhaus, File)

FILE - A woman reacts while sitting in a taxi as different television networks call the presidential race for Barack Obama, in New York on Tuesday, Nov. 4, 2008. (AP Photo/Anja Niedringhaus, File)

FILE - A young Afghan girl plays with a broken shovel outside her makeshift house at a refugee camp in Kabul, Afghanistan, Friday, May 10, 2013. Thousands of Afghans displaced by the war in their own country live in slum-like conditions in refugee camps on the edge of the capital. (AP Photo/Anja Niedringhaus, File)

FILE - Seen through the eye grid of a burqa, women walk through a market in Kabul, Afghanistan on Thursday, April 11, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A fruit seller lifts his son by his cheeks in the center of Kandahar, Afghanistan, Wednesday, March 12, 2014. (AP Photo/Anja Niedringhaus, File)

FILE - Children peek out of a bus as they leave school in Wajah Khiel, Swat Valley, Pakistan on Friday, Oct. 4, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A child is administered a polio vaccination by a district health team worker outside a children’s hospital in Peshawar, Pakistan on Wednesday, May 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Day laborer Zekrullah, 23, takes a break from preparing brick kilns at a factory on the outskirts of Kabul, Afghanistan, Thursday, Nov 7, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Journalists, including Associated Press photographer Anja Niedringhaus, reflected in the window at lower center, surround the car of Bouthaina Shaaban, advisor to Syrian President Assad, as she leaves after meeting with the Syrian opposition at the United Nations headquarters in Geneva, Switzerland, Switzerland, Monday, Jan. 27, 2014. On April 4, 2014, outside a heavily guarded government compound in eastern Afghanistan, Niedringhaus was killed by an Afghan police officer as she sat in her car. She was 48 years old. (AP Photo/Anja Niedringhaus, File)

If she had lived, there would have been so many more photos.

Anja could have gone to Kabul for the chaotic U.S. withdrawal, and to war-shattered Ukraine after the Russian invasion. She would have been at the Olympics, and at center court at Wimbledon. She would have been at all the places where compassionate photographers with trained eyes make it their business to be.

But on April 4, 2014, outside a heavily guarded government compound in eastern Afghanistan, Associated Press photographer Anja Niedringhaus was killed by an Afghan police officer as she sat in her car. She was 48 years old. Her colleague Kathy Gannon, who was sitting beside her, was badly wounded in the attack.

Anja had a convulsive laugh, a thick German accent and an irrepressible decency that elicited trust from the people on the other side of her lens. She trusted them back, making photographs that captured their struggle for humanity, even in some of the world’s most difficult places.

FILE - A picture of Afghan President Hamid Karzai hangs on a wall in the main room of the district municipality in eastern Kabul, Afghanistan, March 29, 2014, ahead of the April 5, 2014, election to choose a new president. (AP Photo/Anja Niedringhaus, File)

FILE - A picture of Afghan President Hamid Karzai hangs on a wall in the main room of the district municipality in eastern Kabul, Afghanistan, March 29, 2014, ahead of the April 5, 2014, election to choose a new president. (AP Photo/Anja Niedringhaus, File)

The three of us became friends in Sarajevo in the early 1990s, when ethnic fighting was savaging the former Yugoslavia and a generation of young photojournalists came into their own. Anja was at the European Pressphoto Agency. We were at the AP.

But while Anja was fiercely competitive, she was also fiercely loyal. Soon we were sharing armored cars, unheated hotel rooms, games of Yahtzee and too many Marlboros.

At a time when women journalists were rare in war zones, Anja was best known as a conflict photographer. Her work helped define the wars in Iraq, Afghanistan, and Libya. Some of the most memorable images from those dark pages in history — ones you might well recognize — came from her camera and her vision.

But Anja never made much out of being a woman surrounded by men. And to see only her conflict work would be a mistake.

FILE - An honor guard stands next to men who arrived to mourn the death of late Vice President Field Marshal Mohammed Qasim Fahim outside his house in Kabul, Afghanistan, March 10, 2014. The influential vice president, a leading commander in the alliance that fought the Taliban who was later accused with other warlords of targeting civilian areas during the country's civil war, died March 9, 2014. He was 57. (AP Photo/Anja Niedringhaus, File)

FILE - An honor guard stands next to men who arrived to mourn the death of late Vice President Field Marshal Mohammed Qasim Fahim outside his house in Kabul, Afghanistan, March 10, 2014. The influential vice president, a leading commander in the alliance that fought the Taliban who was later accused with other warlords of targeting civilian areas during the country’s civil war, died March 9, 2014. He was 57. (AP Photo/Anja Niedringhaus, File)

She was one of the great sports photographers, whether capturing Serena Williams jumping for joy after a Wimbledon victory or the immense smile of British runner Mohamed Farah as he takes Olympic gold in the 5,000-meter. She photographed everything from European elections to global summits. She mentored young photographers everywhere she went. She expertly told small stories of everyday life in dozens of countries.

And despite her reputation as a war photographer, very often she found beauty and joy on assignment — even in those difficult places where she spent so much time. And especially in the place where she ultimately lost her life.

Just look at her photos. She found joy in the moment when an Afghan nomad tenderly kissed his infant daughter, and happiness among Afghan girls finally able to go to school. She found beauty as a swimmer waded into Lake Geneva at sunrise.

She did it all. Now she is 10 years gone. And these images — the ones that were so important to her and so important to understanding a jumbled world — are what is left to speak for her.

FILE - A topless Ukrainian protester is arrested by Swiss police after climbing up a fence at the entrance to the center where the World Economic Forum is held in Davos, Switzerland, Jan. 28, 2012. The activists are from the group Femen, which had become popular in Ukraine for staging small, half-naked protests against a range of issues including oppression of political opposition. (AP Photo/Anja Niedringhaus, File)

FILE - A topless Ukrainian protester is arrested by Swiss police after climbing up a fence at the entrance to the center where the World Economic Forum is held in Davos, Switzerland, Jan. 28, 2012. The activists are from the group Femen, which had become popular in Ukraine for staging small, half-naked protests against a range of issues including oppression of political opposition. (AP Photo/Anja Niedringhaus, File)

FILE - Serena Williams of the United States reacts after winning against Zheng Jie of China during a third round women's singles match at the All England Lawn Tennis Championships at Wimbledon, England, June 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Serena Williams of the United States reacts after winning against Zheng Jie of China during a third round women’s singles match at the All England Lawn Tennis Championships at Wimbledon, England, June 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - A nomad kisses his young daughter while watching his herd in Marjah, Helmand province, Afghanistan, Oct. 20, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - A nomad kisses his young daughter while watching his herd in Marjah, Helmand province, Afghanistan, Oct. 20, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Britain's Mohamed Farah celebrates as he crosses the finish line to win the men's 5000-meter final during the athletics in the Olympic Stadium at the 2012 Summer Olympics, London, Aug. 11, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Britain’s Mohamed Farah celebrates as he crosses the finish line to win the men’s 5000-meter final during the athletics in the Olympic Stadium at the 2012 Summer Olympics, London, Aug. 11, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - An umpire watches the ball as a match unfolds on Court 18, as seen through wooden slats, at the All England Lawn Tennis Championships in Wimbledon, London, June 26, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - An umpire watches the ball as a match unfolds on Court 18, as seen through wooden slats, at the All England Lawn Tennis Championships in Wimbledon, London, June 26, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Boys play soccer during a break at their school in Kandahar, southern Afghanistan, Oct 29, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Boys play soccer during a break at their school in Kandahar, southern Afghanistan, Oct 29, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Pakistani children get ready for class at Malala Yousufzai's old school in Mingora, Swat Valley, Pakistan, Oct. 5, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Pakistani children get ready for class at Malala Yousufzai’s old school in Mingora, Swat Valley, Pakistan, Oct. 5, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A woman takes a dip in Lake Geneva at sunrise in Geneva, Switzerland, July 21, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A woman takes a dip in Lake Geneva at sunrise in Geneva, Switzerland, July 21, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Afghan Army soldiers gather at a training facility on the outskirts of Kabul, Afghanistan, May 8, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Afghan Army soldiers gather at a training facility on the outskirts of Kabul, Afghanistan, May 8, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Injured U.S. Marine Cpl. Burness Britt reacts after being lifted onto a medevac helicopter from the U.S. Army's Task Force Lift "Dust Off," Charlie Company 1-214 Aviation Regiment, June 4, 2011. Britt was wounded in an IED strike near Sangin, in the Helmand Province of southern Afghanistan. During his first operation in Afghanistan he suffered a stroke and became partially paralyzed. (AP Photo/Anja Niedringhaus, File)

FILE - Injured U.S. Marine Cpl. Burness Britt reacts after being lifted onto a medevac helicopter from the U.S. Army’s Task Force Lift “Dust Off,” Charlie Company 1-214 Aviation Regiment, June 4, 2011. Britt was wounded in an IED strike near Sangin, in the Helmand Province of southern Afghanistan. During his first operation in Afghanistan he suffered a stroke and became partially paralyzed. (AP Photo/Anja Niedringhaus, File)

FILE - A woman reacts while sitting in a taxi as different television networks call the presidential race for Barack Obama, Nov. 4, 2008, in New York. (AP Photo/Anja Niedringhaus, File)

FILE - A woman reacts while sitting in a taxi as different television networks call the presidential race for Barack Obama, Nov. 4, 2008, in New York. (AP Photo/Anja Niedringhaus, File)

FILE - A young Afghan girl plays with a broken shovel outside her makeshift house at a refugee camp in Kabul, Afghanistan, May 10, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A young Afghan girl plays with a broken shovel outside her makeshift house at a refugee camp in Kabul, Afghanistan, May 10, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Seen through the eye grid of a burqa, women walk through a market in Kabul, Afghanistan, April 11, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Seen through the eye grid of a burqa, women walk through a market in Kabul, Afghanistan, April 11, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A fruit seller lifts his son by his cheeks in the center of Kandahar, Afghanistan, March 12, 2014. (AP Photo/Anja Niedringhaus, File)

FILE - A fruit seller lifts his son by his cheeks in the center of Kandahar, Afghanistan, March 12, 2014. (AP Photo/Anja Niedringhaus, File)

FILE - Children peek out of a bus as they leave school in Wajah Khiel, Swat Valley, Pakistan, Oct. 4, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Children peek out of a bus as they leave school in Wajah Khiel, Swat Valley, Pakistan, Oct. 4, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - A child is administered a polio vaccination by a district health team worker outside a children's hospital in Peshawar, Pakistan, May 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - A child is administered a polio vaccination by a district health team worker outside a children’s hospital in Peshawar, Pakistan, May 30, 2012. (AP Photo/Anja Niedringhaus, File)

FILE - Day laborer Zekrullah takes a break from preparing brick kilns at a factory on the outskirts of Kabul, Afghanistan, Nov. 7, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Day laborer Zekrullah takes a break from preparing brick kilns at a factory on the outskirts of Kabul, Afghanistan, Nov. 7, 2013. (AP Photo/Anja Niedringhaus, File)

FILE - Journalists, including Associated Press photographer Anja Niedringhaus, reflected in the window at lower center, surround the car of Bouthaina Shaaban, advisor to Syrian President Assad, as she leaves after meeting with the Syrian opposition at the United Nations headquarters in Geneva, Switzerland, Jan. 27, 2014. On April 4, 2014, outside a heavily guarded government compound in eastern Afghanistan, Niedringhaus was killed by an Afghan police officer as she sat in her car. She was 48 years old. (AP Photo/Anja Niedringhaus, File)

FILE - Journalists, including Associated Press photographer Anja Niedringhaus, reflected in the window at lower center, surround the car of Bouthaina Shaaban, advisor to Syrian President Assad, as she leaves after meeting with the Syrian opposition at the United Nations headquarters in Geneva, Switzerland, Jan. 27, 2014. On April 4, 2014, outside a heavily guarded government compound in eastern Afghanistan, Niedringhaus was killed by an Afghan police officer as she sat in her car. She was 48 years old. (AP Photo/Anja Niedringhaus, File)

Jacqueline Larma is deputy director of photography for special projects for The Associated Press. Enric Marti is deputy director of photography for enterprise. Both are veteran AP photographers.

reference assignment c

COMMENTS

  1. c++

    An important detail about references that I think you're missing is that once the reference is bound to an object, you can never reassign it. From that point forward, any time you use the reference, it's indistinguishable from using the object it refers to. As an example, in your first piece of code, when you write. q = "World";

  2. Reference initialization

    C++98. a reference to const-qualified type initialized with a type which is not reference-compatible but has a conversion function to a reference- compatible type was bound to a temporary copied from the return value (or its base class subobject) of the conversion function. bound to the return value (or its base class subobject) directly.

  3. The GNU C Reference Manual

    This is a reference manual for the C programming language as implemented by the GNU Compiler Collection (GCC). Specifically, this manual aims to document: The 1989 ANSI C standard, commonly known as "C89". The 1999 ISO C standard, commonly known as "C99", to the extent that C99 is implemented by GCC. The current state of GNU extensions ...

  4. References in C++

    There are multiple applications for references in C++, a few of them are mentioned below: 1. Modify the passed parameters in a function : If a function receives a reference to a variable, it can modify the value of the variable. For example, the following program variables are swapped using references. Example: 2.

  5. References, C++ FAQ

    For example, with a single type you need both an operation to assign to the object referred to and an operation to assign to the reference/pointer. This can be done using separate operators (as in Simula). For example: Ref<My_type> r :- new My_type; r := 7; // assign to object r :- new My_type; // assign to reference

  6. Reference declaration

    A reference is required to be initialized to refer to a valid object or function: see reference initialization.. The type "reference to (possibly cv-qualified) void " cannot be formed. Reference types cannot be cv-qualified at the top level; there is no syntax for that in declaration, and if a qualification is added to a typedef-name or decltype specifier, (since C++11) or type template ...

  7. 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.

  8. Pass By Reference In C

    Applications. The pass-by-reference method is used when we want to pass a large amount of data to avoid unnecessary memory and time consumption for copying the parameters. It is used where we want to modify the actual parameters from the function. It is used to pass arrays and strings to the function.

  9. 12.3

    An lvalue reference (commonly just called a reference since prior to C++11 there was only one type of reference) acts as an alias for an existing lvalue (such as a variable).. To declare an lvalue reference type, we use an ampersand (&) in the type declaration: int // a normal int type int& // an lvalue reference to an int object double& // an lvalue reference to a double object

  10. Reference and Value Semantics

    Value (or "copy") semantics mean assignment copies the value, not just the pointer. C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the ...

  11. C Operator Precedence

    They are derived from the grammar. In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands. Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always ...

  12. C++ Can You Reassign a Reference? Reference Reassignment Rules

    Summary of Reference Reassignment in C++. To sum it all up, attempting to reassign a reference in C++ is a cardinal sin. It's a strict no-go and the compiler won't hesitate to put you in your place. Final Thoughts on Using References in C++. References are powerful allies in the world of C++, but they have their own code of conduct.

  13. Assigning reference to a variable in C++

    y = testRef(x); // assigning testRef(x) which is int& to y which is int. return 0; It is possible because it makes sense. Life would be very difficult if one couldn't construct objects from references. The assignment means "assign the value of the object the reference refers to ( x) to the LHS ( y ).

  14. Rvalue reference declarator: &&

    Holds a reference to an rvalue expression. Syntax. rvalue-reference-type-id: type-specifier-seq && attribute-specifier-seq opt ptr-abstract-declarator opt. Remarks. Rvalue references enable you to distinguish an lvalue from an rvalue. Lvalue references and rvalue references are syntactically and semantically similar, but they follow slightly ...

  15. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

  16. CS107 Assignment 0: Intro to Unix and C

    The C library function atoi can be used to do this. Review the man page (man atoi) or look in your C reference to get acquainted with this function. Testing. Now let's test the program implementation. The Sanity Check tool is included in the assignment starter project, and acts as a testing aid.

  17. Assignment of Course Number to GIS Specialist (GISS) Recurrency ...

    Assignment of Course Number to GIS Specialist (GISS) Recurrency Training. Submitted by Anonymous (not verified) on Wed, 04/12/2023 - 16:56. Date. Sun, 12/12/2021 - 12:00. ... References: WFSTAR 2023 Fire Year in Review module. WFSTAR 2024 Core Component Module Packages. 2024 NWCG Executive Board Annual Letter Date: March 6, 2024

  18. Ethics code references

    References for ethics codes follow the same format as reports. When the author and publisher are the same (as in the examples), omit the publisher name to avoid repetition. To cite a specific section of an ethics code, create a reference to the full code and then indicate the specific section in the in-text citation.

  19. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  20. Mexico breaks diplomatic ties with Ecuador after embassy raid

    QUITO, Ecuador (AP) — Mexico's government severed diplomatic ties with Ecuador after police broke into the Mexican Embassy to arrest a former Ecuadorian vice president, an extraordinary use of force that shocked and mystified regional leaders and diplomats. Ecuadorian police late Friday broke through the external doors of the embassy in the ...

  21. April 2, 2024, update for PowerPoint 2016 (KB5002568)

    PowerPoint 2016. This article describes update 5002568 for Microsoft PowerPoint 2016 that was released on April 2, 2024. Be aware that the update in the Microsoft Download Center applies to the Microsoft Installer (.msi)-based edition of Office 2016. It doesn't apply to the Office 2016 Click-to-Run editions, such as Microsoft Office 365 Home.

  22. variables

    10. I once wrote a prototype of a version of C# that had that feature; you could say: int x = 123; ref int y = ref x; and now x and y would be aliases for the same variable. We decided to not add the feature to the language; if you have a really awesome usage case I'd love to hear it.

  23. Jerry Seinfeld's New Netflix Movie 'Unfrosted' Is All ...

    Unfrosted looks like a fun 1960s' comedy about the intersection of breakfast and capitalism, and how a pretty mediocre, undeniably bland food item became a massive hit—kind of like most of the ...

  24. For Commanders, Monumental's deal to stay in D.C. could have ripple

    Two stadium-deal experts acknowledged D.C.'s commitment of $515 million to Monumental is money the city can't give the Commanders, but they stopped short of saying it hurt the city's ability ...

  25. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  26. Solar eclipse maps show 2024 totality path, peak times and how much of

    A total solar eclipse crosses North America on April 8, 2024, with parts of 15 U.S. states within the path of totality. Maps show where and when astronomy fans can see the big event. The total ...

  27. c++

    25. A C++ 'reference' can only be initialized, not assigned: ref1=value2; // equivalent to 'value1=value2'. Therefor, an object containing a reference can only be initialized, too! So indeed: if you need assignment on a class, that class cannot have reference member variables. (as a matter of fact, it could, but the assignment cannot make these ...

  28. Iowa vs. Connecticut was ESPN's highest-rated basketball game ever

    The Final Four game between Iowa and Connecticut on Friday was the most-watched basketball game ever aired on ESPN; an average of 14.2 million viewers tuned in, and the broadcast peaked at 17 ...

  29. std::vector<T,Allocator>:: assign

    std::vector<T,Allocator>:: assign. Replaces the contents of the container. 1) Replaces the contents with count copies of value value. 2) Replaces the contents with copies of those in the range [first,last). The behavior is undefined if either argument is an iterator into *this . This overload has the same effect as overload (1) if InputIt is an ...

  30. 10 years after her killing, Anja Niedringhaus' photos speak for her

    AP PHOTOS: 10 years after her killing, Anja Niedringhaus' photos speak for her. FILE - A girl tries to peer through the holes of her burqa as she plays with other children in the old town of Kabul, Afghanistan, April 7, 2013. Despite Associated Press photographer Anja Niedringhaus' reputation as a war photographer, very often she found ...