C/C++-传值/地址的区别

文章目录

高精度问题[1](#1) ,涉及了对调用函数的传值/传引用(地址)的区别。

  1. Is it faster to pass a value or an address for a function in C/C++? Why?

In C and C++, whether it's faster to pass a value or an address (pointer/reference) to a function can depend on several factors, including the size of the data being passed and the architecture of the system . Here's a general guideline:
Passing by Value

When you pass a value to a function, a copy of the data is made .

For small and simple data types (like int, char, float, etc.), passing by value is usually very fast and often the preferred method because the overhead of copying the data is minimal.

However, for large structures or complex objects (like large arrays, structures, or class instances), passing by value can be inefficient because it involves creating a copy of the entire data structure, which can be time-consuming and memory-intensive.
Passing by Address (Pointers/References)

When you pass the address of a variable (using pointers in C or references/pointers in C++), you are passing a memory address. This avoids copying the entire data structure.

For large or complex data types, passing by address is generally more efficient because only the address (typically the size of a machine word ) is copied, not the entire data structure.
Passing by address is also essential when the function needs to modify the original data.

However, for small data types, the overhead of dereferencing a pointer or reference (accessing the data at the address) might make passing by address less efficient than passing by value.
Other Considerations
Cache Locality: Passing by value can sometimes be more cache-friendly, as it ensures that the data is copied close to where it's used, which can be faster for small data sizes.
Safety: Passing by address can lead to issues like dangling pointers, whereas passing by value avoids such problems as each call operates on its own copy.
Readability and Design: Sometimes, the choice between passing by value or by address is also influenced by design considerations and readability, not just performance.
Conclusion

Small Data Types: Pass by value (unless you need to modify the original data).

Large or Complex Data Types: Pass by address (pointers or references), especially if the function needs to modify the original data or if making a copy of the data would be too expensive.

Ultimately, the best choice can also depend on the specific requirements of your application and the behavior of your compiler and hardware. In performance-critical code, it's often a good idea to benchmark both approaches if you're unsure.

  1. Can you give an example based on passing a value versus an address?

Let's consider an example in C where we compare passing a value (by value) with passing an address (by pointer). We'll use a simple function that modifies a data item to illustrate the difference.
Example: Passing by Value

c 复制代码
#include <stdio.h>

void incrementByValue(int num) 
{
   num += 1; // Increment the copy of the variable
}

int main() 
{
   int a = 5;
  incrementByValue(a); // Passes a copy of 'a' to the function
   printf("a after incrementByValue: %d\n", a); // 'a' remains unchanged
   return 0;
}

In this example, incrementByValue receives a copy of the variable a. Changes made to num inside the function do not affect a in the main function.
Example: Passing by Address

c 复制代码
#include <stdio.h>

void incrementByPointer(int *num) 
{
   *num += 1; // Increment the actual variable pointed by 'num'
}

int main() 
{
   int a = 5;
   incrementByPointer(&a); // Passes the address of 'a' to the function
   printf("a after incrementByPointer: %d\n", a); // 'a' is changed
   return 0;
}

In this second example, incrementByPointer receives a pointer to a. Changes made to the value pointed to by num affect the original variable a in the main function.
Conclusion

Passing by Value: The function gets a copy of the data, and modifications inside the function do not affect the original variable.

Passing by Address: The function gets a pointer to the data, and modifications are made to the original variable.

Passing by value is generally used when you don't need to modify the original variable or when dealing with simple data types. Passing by address is used when you need to modify the original variable or when passing large/complex data types to avoid the overhead of copying.

  1. "when passing large/complex data types to avoid the overhead of copying" Give an example of this situation?

Let's consider an example where we have a large data structure, such as a big array or a struct with multiple fields. In this case, passing the entire structure by value (making a copy) can be inefficient due to the overhead of copying all the data. Passing a pointer or reference to the structure is much more efficient, as it avoids this overhead.
Example: Passing a Large Structure

Suppose we have a large structure representing a 3D model with many vertices:

c 复制代码
#include <stdio.h>

#define NUM_VERTICES 1000

typedef struct 
{
   float x, y, z;
} Vertex;

typedef struct 
{
   Vertex vertices[NUM_VERTICES];
} Model;

// Function to translate the model by some offset
void translateModel(Model *model, float offsetX, float offsetY, float offsetZ) 
{
   for (int i = 0; i < NUM_VERTICES; i++) 
   {
       model->vertices[i].x += offsetX;
       model->vertices[i].y += offsetY;
       model->vertices[i].z += offsetZ;
   }
}

int main() 
{
   Model myModel;

   // Initialize myModel with some data
   // ...

   // Translate the model
   translateModel(&myModel, 1.0, 1.0, 1.0);

   // Further processing...
   // ...

   return 0;
}

In this example:

We define a Model struct containing an array of 1000 Vertex structs.

The translateModel function translates each vertex of the model by an offset. It takes a pointer to a Model instead of the whole Model object.

In the main function, we pass the address of myModel to translateModel.
Efficiency of Passing by Address

Memory Efficiency: Only the address of myModel is passed to translateModel, not the entire structure. This is much more efficient than copying the entire Model structure, which contains 1000 Vertex structures.

Performance: Passing a large structure by value can significantly slow down the program, especially in performance-critical applications like graphics, simulations, or large-scale data processing.

Functionality: By passing the address, any modifications translateModel makes to myModel will be reflected in the myModel object in the main function.

In summary, for large or complex data types like this, passing by address is more efficient in terms of both memory and performance. It also allows the function to modify the original data structure.


  1. 1: https://www.acwing.com/problem/content/793/ ↩︎
相关推荐
南境十里·墨染春水6 分钟前
C++传记(面向对象)虚析构函数 纯虚函数 抽象类 final、override关键字
开发语言·c++·笔记·算法
2301_7971727516 分钟前
基于C++的游戏引擎开发
开发语言·c++·算法
比昨天多敲两行1 小时前
C++ 二叉搜索树
开发语言·c++·算法
Season4501 小时前
C++11之正则表达式使用指南--[正则表达式介绍]|[regex的常用函数等介绍]
c++·算法·正则表达式
问好眼2 小时前
《算法竞赛进阶指南》0x04 二分-1.最佳牛围栏
数据结构·c++·算法·二分·信息学奥赛
海海不瞌睡(捏捏王子)2 小时前
C++ 知识点概要
开发语言·c++
蓝凌y3 小时前
51单片机之外部中断
c语言·单片机·嵌入式硬件
AF_INET63 小时前
RV1126B开发板学习篇(二)v4l2+mpp编码
c语言·经验分享·音视频·视频编解码·嵌入式软件·rv1126b
minji...4 小时前
Linux 进程信号(二)信号的保存,sigset_t,sigprocmask,sigpending
linux·运维·服务器·网络·数据结构·c++·算法
小菜鸡桃蛋狗6 小时前
C++——类和对象(下)
开发语言·c++