搜尋此網誌

2025年8月26日星期二

Writing functions in C++

std::string name = "Alice";

A function prototype in C++ is a declaration of a function that tells the compiler about the function's name, return type, and parameters—without actually defining what the function does.

When we say "a function doesn't return a value" in C++, we mean that the function performs its task but doesn't give any result back to the part of the program that called it. Imagine you ask someone to turn off the lights. They do it, but they don’t hand you anything afterward—they just complete the action. That’s a void function.

string& in C++ means you're working with a reference to a std::string object.

In C++, a function is a reusable block of code that performs a specific task. When you call a function, it can either return a value or simply perform an action without returning anything.

In C++, an identifier is the name used to identify a variable, function, class, array, or any other user-defined element.

Microsoft Copilot

Free computer time

The better I got at coding, the more I wanted to do something real --- to write a program that might truly be useful to someone. It was the same urge I had a few years earlier when I'd realize that no matter how cool a picture I could draw of a bridge or a rocket, I could never build one in the real world. This was different. With a computer, I felt like anything I could image, I could create.

十三歲的比爾・蓋茲在編程方面越進步,就越想做一些真正的事情——寫一個或許能對某人真正有用的程式。他回憶道,這種欲望童年的感覺一樣,那時他意識到,無論小時候能畫出多麼有型的橋樑或火箭,都無法在現實世界中建造它們。但這次不同,有了電腦,他覺得任何他能想像的東西,都能創造出來。

meatloaf: meat, onions, etc. that are cut into very small pieces, mixed together and shaped like a loaf of bread and then baked

trivial: not important or serious; not worth considering

toll: the amount of damage or the number of deaths and injuries that are caused in a particular war, disaster, etc.

envision: to imagine what a situation will be like in the future, especially a situation you intend to work towards

airfield: an area of flat ground where military or private planes can take off and land

artillery: DJ[ɑ:ˋtiləri] large, heavy guns which are often moved on wheels

destroyer: a small fast ship used in war, for example to protect larger ships

offensive: attack

gauge: DJ[geidʒ] to measure something accurately using a special instrument

recuperate: to get back your health, strength or energy after being ill, tired, injured, etc.

fighter: a fast military plane designed to attack other aircraft

infantry: ​soldiers who fight on foot

odds: the degree to which something is likely to happen

peel off: to leave a group of vehicles, aircraft, etc. and turn to one side

curfew: a time when children must be home in the evening

wage: to begin and continue a war, a battle, etc.

demote: to move somebody/something to a lower position or rank, often as a punishment

owe: to have to pay somebody for something that you have already received or return money that you have borrowed

brag: to talk too proudly about something you own or something you have done

hardcore: highly committed in one's support for or dedication to something; denoting an extreme or intense example of something

banish: to order somebody to leave a place, especially a country, as a punishment

bypass: to ignore a rule, an official system or somebody in authority, especially in order to get something done quickly

lenient: not as strict as expected when punishing somebody or when making sure that rules are obeyed

summon: to order somebody to come to you

beard: DJ[biəd]

sternly: in a serious way that often shows that you do not approve of somebody/something; in a way that shows you expect somebody to obey you

berate: to criticize or speak angrily to somebody because you do not approve of something they have done

off-limits (to somebody) (of a place) where people are not allowed to go


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

www.merriam-webster.com

Translated with the help of AI and edited.

2025年8月21日星期四

Passing values to a function

It’s not that one is universally better --- pointers and references are different tools, each with its own strengths and trade‑offs. The “better” choice depends on your intent and the constraints of your code.

trade-off: the act of balancing two things that are opposed to each other

In C++, “taking an argument” usually means receiving input values into a function so it can work with them.

In C++, the return statement is how a function hands control (and optionally a value) back to its caller. Think of it as the function’s “exit door” — once return runs, the function stops executing immediately.

For void functions, you can:
- Omit return entirely, or
- Use return; to exit early without a value:

In main
- return 0; → program ended successfully
- Non‑zero values (e.g., return 1;) → indicate an error or abnormal termination to the operating system

In C++, the difference between taking arguments by address (pointers) and by reference is as follows:

By Address (Pointers):

You pass the memory address of the variable.
Syntax: Use an asterisk * in the function parameter and an ampersand & when calling the function.
Example: void swap(int *x, int *y) and called with swap(&a, &b).
Requires dereferencing inside the function using the * operator.

By Reference:

You pass the variable itself, but it acts as an alias to the original variable.
Syntax: Use an ampersand & in the function parameter.
Example: void swap(int &x, int &y) and called with swap(a, b).
No need for dereferencing inside the function.

Using references is generally safer and simpler because it avoids the need for explicit pointer manipulation.

Mainly by Microsoft Copilot

2025年8月19日星期二

fundamental code

A converted car dealership refers to a former car dealership building that has been repurposed for a different use.

pricey: expensive

Smashed Piñata Cakes only uses the highest-quality ingredients.

creep: to move with your body close to the ground; to move slowly on your hands and knees

sneak: to go somewhere secretly, trying to avoid being seen

scenic: having beautiful natural scenery

détente: an improvement in the relationship between two or more countries which have been unfriendly towards each other in the past

lenient: not as strict as expected when punishing somebody or when making sure that rules are obeyed

grateful: feeling or showing thanks because somebody has done something kind for you or has done as you asked

overstate: to say something in a way that makes it seem more important than it really is

sophomore: DJ[ˋsɔfəmɔ:]

A wartime decoy is a military tactic using deceptive devices to mislead the enemy about the location or strength of forces and equipment.

undervalue: to not recognize how good, valuable or important somebody/something really is

"Outliers: The Story of Success" is a non-fiction book written by Canadian writer Malcolm Gladwell.

deliberate: done on purpose rather than by accident

underwhelming: ​not impressing or exciting you at all

wield something: to have and use power, authority, etc.

mint: to make a coin from metal

slot machine: a machine that you put coins into to play a game in which you win money if particular pictures appear together on the screen; a similar game, played online

payout: a large amount of money that is given to somebody

aforementioned: mentioned before, in an earlier sentence

if there is a scarcity of something, there is not enough of it and it is difficult to obtain it

handful: a small number of people or things

snippet: a small piece of information or news

tantalizing: making you want something that you cannot have or do

stumble upon: to discover something/somebody unexpectedly

workaround: a way of working, especially with a piece of software, that avoids a particular problem but does not actually solve the problem

scrap: a small piece of something, especially paper, cloth, etc.

crumple: to press or crush something into folds; to become pressed, etc. into folds

dumpster: a large open container for putting old bricks, rubbish, etc. in. The Dumpster is then loaded on a lorry and taken away.

dregs: the last drops of a liquid, mixed with little pieces of solid material that are left in the bottom of a container

Polystyrene foam cups are often referred to as Styrofoam.

nimble: able to move quickly and easily

quarry: a place where large amounts of stone, etc. are dug out of the ground

terse: using few words and often not seeming polite or friendly

off-limits (to somebody) (of a place) where people are not allowed to go

laborious: taking a lot of time and effort

explicitly: clearly or directly, so that the meaning is easy to understand

novice: a person who is new and has little experience in a skill, job or situation

impenetrable: impossible to understand

Spacewar! is a space combat video game developed in 1962 by Steve Russell in collaboration with Martin Graetz, Wayne Wiitanen, Bob Saunders, Steve Piner, and others.

torpedo: a long, narrow bomb that is fired under the water from a ship or submarine and that explodes when it hits a ship, etc.

decipher: decipher something to convert something written in code into normal language

sprawl: to sit, lie or fall with your arms and legs spread out in a relaxed or careless way

Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

2025年8月17日星期日

Functions in C++

Modularity refers to the degree to which a system's components can be separated and recombined, often for increased flexibility and variety of use. It's a concept that can be applied across various disciplines, including engineering, computer science, and biology.

A simple example of a function in C++ that returns a value:

#include <iostream>

using namespace std;

int multiply(int x, int y) {

    return x * y;

}

int main() {

    int result = multiply(4, 5);

    cout << "The result is: " << result << endl;  // Output: The result is: 20

    return 0;

}

A function is a reusable block of code that performs a specific task. It can take inputs (parameters), do something, and optionally return a value.

Parameter: a variable in the function definition that receives a value

Argument: the actual value passed to the function when it is called

Use const in parameters when you don’t want them modified

A global function is defined outside of any class and can be accessed from anywhere in the file (or other files if declared properly).

Functions defined inside a class are called member functions. They operate on the data members of the class and can be either public or private.

In C++, a function signature is the part of a function declaration that includes the function name and the parameter types (but not the return type or parameter names).

In C++, the return type of a function specifies the type of value that the function will send back to the caller when it finishes executing.

What Is a Return Type?
It’s the data type declared before the function name that tells the compiler what kind of result to expect.

A function declaration tells the compiler, “This function exists, and here’s how it should be called.”

It does not contain the body of the function—just the signature and return type.

A function definition provides the actual implementation of a function. It includes:
- The return type
- The function name
- The parameter list
- The body (code that runs when the function is called)

A function prototype is a declaration that tells the compiler, “This function exists, and here’s how it should be called.”

It’s usually placed before main() or in a header file so the compiler knows about the function before it’s used.

Microsoft Copilot

2025年8月12日星期二

Quiz

In C++, a struct (short for "structure") is a user-defined data type that groups related variables under one name. It’s similar to a class, but by default, its members are public rather than private.

In C++, double is a primitive data type used to store floating-point numbers with double precision. That means it can represent decimal numbers with more digits and greater range than a float.

The line for (Resource& r : resources) is a range-based for loop in C++, and it means:
“For each Resource object r in the container resources, do something.”

The switch statement in C++ is a control structure used to execute different blocks of code based on the value of a variable—typically an int, char, or enum. It’s a cleaner alternative to multiple if-else statements when you're checking the same variable against many values.

for (declaration : container) {
    // loop body
}

Microsoft Copilot

Ranged for loops

traverse: cross

for (initialization; condition; update) {

    // Code to execute repeatedly

}


average += laptimes[i];

average = average + laptimes[i];


for (auto x : laptimes)

“For each element x in the container laptimes, do something with x.”
  • auto: Automatically deduces the type of x (e.g., double if laptimes is a vector)
  • x: A copy of each element in laptimes
  • :: Reads as “in” — like “for each x in laptimes


Microsoft Copilot

Testing a mainframe computer

commute: to travel regularly by bus, train, car, etc. between your place of work and your home

carpool: a group of car owners who take turns to drive everyone in the group to work, so that only one car is used at a time

cram: to learn a lot of things in a short time, in preparation for an exam

convertible: (of a car) having a roof that you can fold down or take off

savior: a person who rescues somebody/something from a dangerous or difficult situation

The French Resistance was a collection of groups that fought the Nazi occupation and the collaborationist Vichy regime in France during the Second World War.

decoy: a thing or a person that is used to trick somebody into doing what you want them to do, going where you want them to go, etc.

divert: to take somebody’s thoughts or attention away from something

jolt: to give somebody a sudden shock, especially so that they start to take action or deal with a situation

talk down to: to speak to somebody as if they were less important or intelligent than you

mainframe computer: a large, powerful computer, usually the center of a network and shared by many users

upmarket: in a way that involves buying or selling goods and services that are expensive and of high quality

entice: to persuade somebody/something to go somewhere or to do something, usually by offering them something

venture: a business project or activity, especially one that involves taking risks

upperclassman: (in the US) a male student in the last two years of high school or college

dealership: a business that buys and sells products, especially cars, for a particular company; the position of being a dealer who can buy and sell something

within earshot: near enough to hear somebody/something or to be heard

self-proclaimed: giving yourself a particular title, job, etc. without the agreement or permission of other people

anarchist: a person who believes that laws and governments are not necessary

hippie: a person who rejects the way that most people live in Western society, often having long hair, wearing brightly colored clothes and taking illegal drugs. The hippie movement was most popular in the 1960s.

hangout: a place where somebody lives or likes to go often

pepperoni: a type of spicy sausage

rigor: the fact of being strict or severe

afterthought: a thing that is thought of, said or added later, and is often not carefully planned

assurance: a statement that something will certainly be true or will certainly happen, particularly when there has been doubt about it

stipulation: a clear and definite statement that something must be done, or about how it must be done

paradoxically: in a way that seems strange, impossible or unlikely because it has two opposite features or contains two opposite ideas


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

2025年8月8日星期五

Computer room

    比爾·蓋茲喜歡電腦,電腦讓他思考。電腦對他馬虎的思維嚴酷無情。電腦要求他在邏輯上貫徹始終,在細節上小心注意。

    I loved how the computer forced me to think. It was completely unforgiving in the face of mental sloppiness. It demanded that I be logically consistent and pay attention to details.

disparate: so different from each other that they cannot be compared or cannot work together

rudimentary: dealing with only the most basic matters or ideas

ominously: in a way that suggests that something bad is going to happen in the future

elegance: the quality in a plan or an idea of being clever but simple

instantaneous: happening immediately

tic-tac-toe: a paper-and-pencil game for two players who take turns marking the spaces in a three-by-three grid, one with Xs and the other with Os.

infer: deduce

outstrip: to become larger, more important, etc. than somebody/something

sloppiness: ​the fact of showing a lack of care, thought or effort

rigorous: demanding that particular rules, processes, etc. are strictly followed

Algebra is a branch of mathematics that uses symbols, often letters, to represent numbers and their relationships in mathematical expressions and equations.

persevere: to continue trying to do or achieve something despite difficulties

coax: to persuade somebody to do something by talking to them in a kind and gentle way

asterisk: DJ[ˋæstərisk]

rack up: to collect something, such as profits or losses in a business, or points in a competition

blistering: done very fast or with great energy

gaggle: ​a group of noisy people

stoke: to make people feel something more strongly

mosh pit: the place, just in front of the stage, where the audience at a concert of rock music dances and jumps up and down

outdo: to do more or better than somebody else

indeterminate: that cannot be identified easily or exactly

put-upon: treated in an unfair way by somebody because they take advantage of the fact that you are kind or willing to do things

sophomore: ​a student in the second year of a course of study at a college or university

exploit: to treat a person or situation as an opportunity to gain an advantage for yourself

If someone is jockeying for position, they are using whatever methods they can in order to get into a better position than their rivals.

rival: a person, company or thing that competes with another in sport, business, etc.

hand-me-down: ​no longer wanted by the original owner

A Renaissance DJ[rəˋneisəns] man is a term for someone who is knowledgeable, educated, and proficient in many different fields, excelling in a variety of areas.

ICBM: Intercontinental Ballistic Missile

muttonchops: long hair growing down each side of a man's face

goad: stimulate

bait: a person or thing that is used to attract somebody in order to catch them or make them do what you want

gadget: DJ[ˋgædʒit] a small tool or device that does something useful

cerebral: relating to the mind rather than the feelings

foursome: a group of four people taking part in a social activity or sport together

leveler: an event or a situation that makes everyone equal whatever their age, importance, etc.

RAND is a nonprofit institution that helps improve policy and decision-making through research and analysis.

kooky: strange or crazy

hindsight: the understanding that you have of a situation only after it has happened and that means you would have done things in a different way

de facto: (from Latin, formal) existing as a fact although it may not be legally accepted as existing

overseer: a person or an organization that is responsible for making sure that a system is working as it should

thrilled: very excited and pleased

poke: to push something somewhere or move it in a particular direction with a small quick movement

squabble: ​a noisy argument about something that is not very important

wrath: extreme anger

tongue-in-cheek: not intended seriously; done or said as a joke

laissez-faire: the policy of leaving things to take their own course, without interfering

oversight: the fact of making a mistake because you forget to do something or you do not notice something

rebuff: rebuff something to refuse a friendly offer, request or suggestion in an unkind way

Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

www.merriam-webster.com

Some explanations are from Google AI Overview.

2025年8月5日星期二

Reference in C++

#include <iostream>

void incrementByReference(int& ref) {
    ref++;  // Directly increments the original variable
}

int main() {
    int value = 20;
    int& rValue = value;  // Declare a reference bound to 'value'
   
    std::cout << "Before: " << value << "\n";  // Prints 20
   
    incrementByReference(rValue);
   
    std::cout << "After:  " << value << "\n";  // Prints 21
   
    // References must be initialized and cannot be reseated
   
    return 0;
}

References in C++ act as true aliases for existing objects.

Once you bind a reference to an object, any operation through that reference directly

affects the original. There’s no extra indirection or separate storage - think of the

reference as a permanent nickname for the object.


Ideal for function parameters when you want to modify the caller’s variable.

value is the caller’s variable (actual parameter) in the main() function.

Microsoft and GitHub Copilot

Pointer in C++

#include <iostream>

void incrementByPointer(int* ptr) {
    if (ptr) {
        (*ptr)++;  // Dereference pointer, then increment the pointee
    }
}

Line 1. Function Signature - Return type is void, so nothing comes back to the caller. - Parameter is int* ptr, a pointer to an int.

Line 2. Null Check
Guarding against a null pointer prevents undefined behavior if someone accidentally calls
incrementByPointer(nullptr).

Line 3. Dereference & Increment
- The parentheses ensure you dereference ptr first, yielding the int it points to.
- The ++ then increments that int in place.
Note: Writing ptr++ would advance the pointer itself, not the value it points to.

int main() {
    int value = 10;
    int* pValue = &value;  // Declare a pointer and take the address of 'value'
   
    std::cout << "Before: " << value << "\n";  // Prints 10
   
    incrementByPointer(pValue);
   
    std::cout << "After:  " << value << "\n";  // Prints 11

When you see both ptr and pValue in the code, they’re actually two separate pointer variables that refer

to the same int in memory, but they live in different scopes and serve different roles.

Roles and Scope

    pValue

Declared in main().

Holds the address of value.

Its lifetime is the entire execution of main.

You use it to pass &value into functions or perform pointer arithmetic in main.

    ptr

Declared as a parameter in incrementByPointer(int* ptr).

Receives a copy of pValue (the address).

Its lifetime is the duration of the function call.

You use it inside incrementByPointer to modify the pointee.


The literal "\n" represents a single newline character in C++ strings.

When inserted into an output stream, it moves the cursor to the beginning of the next line.

    // Pointer arithmetic example
    int arr[] = {1, 2, 3};
    int* pArr = arr;  // Points to the first element
    std::cout << "Second element via pointer arithmetic: "
              << *(pArr + 1) << "\n";  // Prints 2
   
    return 0;
}

arr decays to int* pointing at the first element.

pArr + 1 advances the pointer by one int (4 bytes on most platforms).

The dereference *(pArr+ 1) yields the second element, exactly like arr[1].

Output:

Second element via pointer arithmetic: 2


Microsoft Copilot

His friend

unruly: not readily ruled, disciplined, or managed

cleft lip: a birth defect characterized by one or more clefts in the upper lip resulting from failure of the embryonic parts of the lip to unite

impediment: a problem, for example a stammer, that makes it more difficult for somebody to speak, hear, etc.

stammer: a problem that somebody has in speaking in which they repeat sounds or words or often stop, before saying things correctly

orthodontia: the treatment of irregularities in the teeth and jaws.

slackly: loosely

A Unitarian minister is a religious leader in the Unitarian or Unitarian Universalist (UU) tradition.

clique: a small group of people who spend their time together and do not allow others to join them

pursue: to do something or try to achieve something over a period of time

tumultuous: involving many difficulties and a lot of change and often violence

assassination: DJ[ə͵sæsiˋneiʃən] the murder of an important or famous person, especially for political reasons

convention: a large meeting of the members of a profession, a political party, etc.

bow out: to stop taking part in an activity, especially one in which you have been successful in the past

vying: vie: to compete strongly with somebody in order to obtain or achieve something

vehemently: ​in a way that shows very strong feelings, especially anger

devour: to read or look at something with great interest and enthusiasm

senator: a member of a senate

senate: one of the two groups of elected politicians who make laws in some countries, for example in the US, Australia, Canada and France. The Senate is smaller than the other group but higher in rank. Many state parliaments in the US also have a Senate.

decry: to strongly criticize somebody/something, especially publicly

conspiracy theory: the belief that a secret but powerful organization is responsible for an event

plot: a secret plan made by a group of people to do something wrong or illegal

idolize: to admire or love somebody very much, possibly too much

LBJ: Lyndon B. Johnson

liberal: a person who supports individual freedom and rights, democracy and free enterprise (= businesses competing against each other with little government control)

carpet: to cover something with a thick layer of something

canvass:  to ask people to support a particular person, political party, etc., either by going around an area and talking to people or by phoning them

flyer: a small sheet of paper that advertises a product or an event and is given to a large number of people

stake out: ​to watch a place secretly, especially for signs of illegal activity

pudgy: ​slightly fat

bump into: (informal) to meet somebody by chance

take on: to begin to have a particular quality, appearance, etc.

machination: a secret and complicated plan

obsess: to completely fill your mind so that you cannot think of anything else, in a way that is not reasonable or normal

mitigate: to make something less harmful, serious, etc.

intrigue: to make somebody very interested and want to know more about something

disquisition: a long complicated speech or written report on a particular subject

ding: to speak with tiresome reiteration

shortcoming: ​a fault in somebody’s character, a plan, a system, etc.

outline: to give a description of the main facts or points involved in something

slog: a hard journey

rugged: (of the landscape) not level or smooth and having rocks rather than plants or trees

slosh: to move around making a lot of noise or coming out over the edge of something

inundate: overflow

fled: flee: to leave a person or place very quickly, especially because you are afraid of possible danger

aside from: except for

notion: ​an idea, a belief or an understanding of something

envision: to imagine what a situation will be like in the future, especially a situation you intend to work towards

Douglas MacArthur (26 January 1880 - 5 April 1964) was an American general who served as a top commander during World War II and the Korean War.

dissect something: to study something closely and/or discuss it in great detail

decipher: to succeed in finding the meaning of something that is difficult to read or understand

"Lucy in the Sky with Diamonds" is a song by the English rock band the Beatles, featured on their 1967 album Sgt. Pepper's Lonely Hearts Club Band.

marvel at: to show or experience great surprise or admiration

flaw: a mistake in something that means that it is not correct or does not work correctly

appointee: a person who has been chosen for a job or position of responsibility

clout: DJ[klaut] power and influence

prodigious: ​very large or powerful and causing surprise; impressive

A clapboard is a type of siding, traditionally made of long, thin, overlapping wooden boards, used to cover the exterior of buildings.

A cog railway is a type of railway that uses a toothed rack rail, usually between the running rails, to climb steep slopes.

hunch over: to bend the top part of your body forward and raise your shoulders and back

rotary: moving in a circle around a central fixed point

A teletype machine, also known as a teletypewriter or teleprinter, is an electromechanical device that transmits and receives typed messages over communication channels.

In computing, time-sharing refers to a method of sharing a computer's resources, typically the CPU, among multiple users or processes concurrently.

concurrently: at the same time

parcel out: to divide something into parts or between several people

caliber: the quality of something, especially a person’s ability

An ordained minister is a member of the clergy who has been formally recognized and authorized by a religious institution to perform religious rites and ceremonies.

freewheeling: not concerned about rules or the possible results of what you do

aeronautical: connected with the science or practice of building and flying aircraft

avid: very enthusiastic about something (often a hobby)

sabbatical: a period of time when somebody, especially a teacher at a university, is allowed to stop their normal work in order to study or travel

sacred: very important and treated with great respect; that must not be changed or challenged

infamous: notorious

trek: a long, hard walk lasting several days or weeks, especially in the mountains

intrepid: very brave; not afraid of danger or difficulties

lease: a legal agreement that allows you to use a building, a piece of equipment or some land for a period of time, usually in return for rent

rummage sale: a sale of old or used clothes, etc. to make money for a church, school or other organization

cutting-edge: at the newest, most advanced stage in the development of something

amusing: funny and giving pleasure

hunch: a feeling that something is true even though you do not have any evidence to prove it

Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

www.merriam-webster.com

Some explanations are from Google AI Overview.